<?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 加牛不辣 on Medium]]></title>
        <description><![CDATA[Stories by 加牛不辣 on Medium]]></description>
        <link>https://medium.com/@wcp1231?source=rss-24229f09b58c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*mawy1wX3bT5K5VnO2R_RTA@2x.jpeg</url>
            <title>Stories by 加牛不辣 on Medium</title>
            <link>https://medium.com/@wcp1231?source=rss-24229f09b58c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 00:00:09 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@wcp1231/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 Implement a Simple Rate Limiter in Spring Webflux]]></title>
            <link>https://medium.com/@wcp1231/how-to-implement-a-simple-rate-limiter-in-spring-webflux-5308c56ea4db?source=rss-24229f09b58c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5308c56ea4db</guid>
            <category><![CDATA[webflux]]></category>
            <category><![CDATA[spring]]></category>
            <category><![CDATA[reactor]]></category>
            <category><![CDATA[token-buckets]]></category>
            <dc:creator><![CDATA[加牛不辣]]></dc:creator>
            <pubDate>Sat, 29 Jun 2024 13:37:56 GMT</pubDate>
            <atom:updated>2024-06-29T13:37:56.442Z</atom:updated>
            <content:encoded><![CDATA[<p>I have a Spring Webflux project, in which there are some background jobs to request a third-party service, such as CRUD certain data. However, the third-party service has a rate limit and if the QPS is too high, it rejects the request and the job fails. So I need to control the rate when requesting this third-party service.</p><p>A common practice is the token bucket algorithm. A normal token bucket algorithm is simple: you try to acquire a token, and if it fails, you wait manually and try again.</p><p>In this scenario, I want to implement a rate limiter based on the <a href="https://projectreactor.io/">Reactor</a> library that returns a Mono when acquiring a token, and the Mono doesn’t emit signal until there is a token available. Here is the code:</p><pre>public class TokenBucket {<br>    private final int capacity;<br>    private final int tokensPerPeriod;<br>    private final AtomicInteger tokens;<br>    private final Queue&lt;MonoSink&lt;Boolean&gt;&gt; waitQueue;<br><br>    public TokenBucket(int capacity, int tokensPerPeriod, Duration refillPeriod) {<br>        this.capacity = capacity;<br>        this.tokensPerPeriod = tokensPerPeriod;<br>        this.tokens = new AtomicInteger(capacity);<br>        this.waitQueue = new ConcurrentLinkedQueue&lt;&gt;();<br><br>        // Schedule token refills<br>        Flux.interval(refillPeriod)<br>                .flatMap(tick -&gt; Mono.fromRunnable(this::refillTokens))<br>                .subscribe();<br>    }<br><br>    private void refillTokens() {<br>        int newTokens = Math.min(capacity, tokens.get() + tokensPerPeriod);<br>        tokens.set(newTokens);<br><br>        while (tokens.get() &gt; 0 &amp;&amp; !waitQueue.isEmpty()) {<br>            MonoSink&lt;Boolean&gt; sink = waitQueue.poll();<br>            if (sink != null) {<br>                tokens.decrementAndGet();<br>                sink.success(true);<br>            }<br>        }<br>    }<br><br>    public Mono&lt;Boolean&gt; acquire() {<br>        return Mono.create(sink -&gt; {<br>            if (tokens.getAndDecrement() &gt; 0) {<br>                sink.success(true);<br>            } else {<br>                // Revert decrement if no tokens available<br>                tokens.incrementAndGet();<br>                waitQueue.add(sink);<br>            }<br>        });<br>    }<br>}</pre><p>Then we can use this rate limiter like this:</p><pre>public class ThirdPartService {<br>    private TokenBucket ratelimiter = <br>        new TokenBucket(10, 1, Duration.ofMillis(100));<br><br>    private Client client;<br><br>    public Mono&lt;List&lt;Data&gt;&gt; list() {<br>        return ratelimiter.acquire()<br>          .flatMap(success -&gt; clent.list());<br>    }<br><br>    public Mono&lt;Data&gt; get(String id) {<br>        return ratelimiter.acquire()<br>          .flatMap(success -&gt; clent.get(id));<br>    }<br><br>    public Mono&lt;Data&gt; create(Data data) {<br>        return ratelimiter.acquire()<br>          .flatMap(success -&gt; clent.create(data));<br>    }<br><br>    public Mono&lt;Data&gt; delete(String id) {<br>        return ratelimiter.acquire()<br>          .flatMap(success -&gt; clent.delete(id));<br>    }<br>}</pre><p>We can call acquire() to get a Mono and then flatMap to make a request to the third-party service, and this request will only be make if there is an available token.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5308c56ea4db" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open Source Idea: Mock Whole Environment]]></title>
            <link>https://medium.com/@wcp1231/open-source-idea-mock-whole-environment-c3b302abc59a?source=rss-24229f09b58c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c3b302abc59a</guid>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[proxy]]></category>
            <dc:creator><![CDATA[加牛不辣]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 14:56:09 GMT</pubDate>
            <atom:updated>2024-03-21T14:56:09.180Z</atom:updated>
            <content:encoded><![CDATA[<h3>Background</h3><p>Writing the effective test code is hard, and maintaining the effective test data is even harder. Especially the business team does not have the time and willingness to write tests by themselves.<br>I usually write integration test code using TestContainer , which provides a mock database. But I’m not sure what’s the best way to mock the dependency servers, or how to integration test that code with external server, such as DB, Cache and MQ. <br>So I was wondering if there could be a tool to mock all the external dependencies of the server and can manage their mock data. How to design a tool to do this.</p><h3>System Design</h3><p>There are two options to mock all the external dependencies:</p><ol><li><strong>Java Agent:</strong> Intercept all dependencies on the client side and add mock feature.</li><li><strong>Transparent Proxy</strong>: Proxy all dependencies’ traffic and mock data.</li></ol><p>The first one is that we can write a agent to intercept the critical path of each external dependency. So that we can get the request data and can mock the response. The advantage of this is that we have direct access request and response objects without the need to decode difference protocols. But the disadvantage is that we have to support difference versions or dialects of these clients for difference code logic. And this can only be used for JVM services.</p><p>The second one is that we can write a proxy to proxy all the network traffic from and to the application, and then we can mock these external dependencies by response fake network data. The advantage of this is we don’t need to consider the diversity of clients and their code details, we only need to decode and encode the network data, their protocol are quite stable. On the other hand, the disadvantage is that we need to digging to these protocols and process this network data like a real server, which is a tough job.</p><p>In the end, I chosen the second one, writing a proxy in Golang, and I was able to lean some knowledge of their protocols as well. I named this proxy <a href="https://github.com/wcp1231/cocoon">Cocoon</a>, inspired by <a href="https://en.wikipedia.org/wiki/Case_Closed:_The_Phantom_of_Baker_Street">Case Closed: The Phantom of Baker Street</a>, there is an immersive VR game console called Cocoon in this film. I hope this proxy will be able to mock whole environments for applications just like the VR game in the film.</p><p>Here is a simple software architecture.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d5mrU2uCXGmFzao1yJYTkg.png" /><figcaption>Software Archiecture</figcaption></figure><p>This proxy listens for TCP connection, and for each new connection it will launches a goroutines and creates a RequestResponseHandler to handle it. In this handler, it read bytes from InBoundConn and identify its protocol. If its protocol is not supported or it needs to pass through, it will write all the bytes to OutBoundConn than proxy its response. Otherwise it decodes the bytes and passes the decode result to mock service. The mock service returns response to InBoundConn based on the mock data loaded from the file.</p><p>There are three data models: Raw Data for raw network data, Generic Message for the result of decoding raw data and using it within the handler, Mock Data for mock config.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-MbKRDPWpq5ofdY7AqaOkw.png" /><figcaption>Data Models</figcaption></figure><p>This proxy currently achieved decode and display HTTP, Dubbo, MongoDB, MySQL and Redis protocols, and supported Mock HTTP and Redis response. But it just barely works.</p><p>The most difficult part at the moment is to design a generic model to hold data decoded from difference protocols and be able to process and present it well. And how to design mock data struct and logic to support remaining protocols such as MongoDB and MySQL.</p><h3>Next Steps</h3><ol><li>Refactoring mock service and support more protocols.</li><li>Polishing the frontend UI.</li><li>Supporting Kafka protocol.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c3b302abc59a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Snowflake ID in Kubernetes]]></title>
            <link>https://towardsdev.com/snowflake-id-in-kubernetes-05f3b53cd42c?source=rss-24229f09b58c------2</link>
            <guid isPermaLink="false">https://medium.com/p/05f3b53cd42c</guid>
            <category><![CDATA[objectid]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[snowflake]]></category>
            <dc:creator><![CDATA[加牛不辣]]></dc:creator>
            <pubDate>Sun, 17 Mar 2024 17:25:19 GMT</pubDate>
            <atom:updated>2024-03-20T17:26:02.911Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, our business team make a tech request to support Snowflake ID in kubernetes. Their application runs as a Deployment on Kubernetes, and they use a snowflake-like algorithm to generate the ID, but there’s nothing in the pod to use as a machine ID. And they tried generating a random number as machine ID, but found there were many id conflicts when two pods had the same machine ID. So they need some help, for example, adding a unique ID to each Pods and using it as a machine ID.</p><h3>How to generate unique ID</h3><p>I researched how to generate unique ID each Pods, there are for approaches:</p><ul><li>Use an external server such as zookeeper or ETCD to provider a unique ID for the application.</li><li>Change to using a StatefulSet to manage the application.</li><li>Use the initContainer to register a unique ID and write it to a file.</li><li>Use the Kubernetes Admission Controller to inject unique ID into the Pod.</li></ul><p>The first one is pretty straightforward. When the application starts, it can read the minimum unused number from the external server, and register that number back to the external server and keep it alive. But it adds external dependencies to the application and makes the architecture more complex. It needs to be carefully considered.</p><p>The second one is simple. We know that StatefulSet is a Kubernetes workload for managing stateful application, and its Pods has unique network identifiers. That is say its Pods have an ordinal index in their name, which can be used as machine ID. However, deploying a stateless business application as a StatefulSet is a irregular use that will make that application harder to manage. It is not a good idea.</p><h4>The third one: initContainer</h4><p>This is the minimum changes solution, not need to changes the application architecture and its workload, and not need to add a admission controller to Kubernetes. It just a simple tool to run in initContainer to request a unique ID.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9YQMP0kbBS1qaYgEDYtPOQ.png" /><figcaption>System Architecture</figcaption></figure><p>More specifically, there is a manager service to get and watch all pods, so it can number each pod. When a pod starts, the client in the initContainer can request to the manager server with the pod name, and then write the unique ID to the file. Then the application can read this unique ID from the file. If the manager service is unavailable, the client can fallback to randomly generating a unique ID. And the client can also be run in a start script.</p><p>Pros:</p><ul><li>Simple. This solution is a simple C/S architecture, and the most of work is done on the server side.</li></ul><p>Cons:</p><ul><li>Not clean enough. It adds an external step to the application startup process.</li></ul><h4>The fourth one: Admission Controller</h4><p><a href="https://kubernetes.io/docs/reference/access-authn-authz/extensible-admission-controllers/">Admission Controller</a> is a Kubernetes plugin that allows you to add custom logic to the Kubernetes API Server, and it can validate or modify the resources being applied.</p><p>We can create an Admission Controller to listen the CREATE and DELETE operation of the Pod.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xKBkmOo-nibVgl8n5aqcPQ.png" /><figcaption>System Architecture</figcaption></figure><p>When the API Server receives an API request, the API Server would send an Admission Review to our Admission Controller. In the case of creating a pod, we can register a unique ID and response to The API Server with a patch where we can inject that unique ID into the pod env. In the case of deleting a pod, we can release its unique ID.</p><p>Pros:</p><ul><li>Application agnostic. Everything is happens in the Kubernetes control panel, and the only thing application knows is that it can get a unique ID from the environment.</li></ul><p>Cons:</p><ul><li>Too deep into Kubernetes. Admission Controller is difficult to test and debug. And if there is a bug or exception, it may influence to all the applications.</li></ul><h3>How MongoDB ObjectId work</h3><p>While doing my research, a question hit to my mind that how dose MongoDB ObjectId handle this situation? We have several applications that use MongoDB as database, will they have id conflict?</p><p>ObjectId is similar to snowflake ID in that it has three part: timestamp, machine ID and counter. According to the <a href="https://www.mongodb.com/docs/manual/reference/method/ObjectId/">latest document</a>, the machine ID is just a random value. So, if two pods with the same machine ID, will there be an id conflict? Probably not. It is because the third part of the ID, the counter, starts with a random value.</p><p>How much of the difference dose it make? Let’s do a simple test.</p><pre>public class SimpleSnowflakeTest {<br>    /**<br>     * A simple snowflakes implementation.<br>     */<br>    static class SimpleSnowflakes {<br>        private final static long START_TIMESTAMP = 1690819200000L;<br>        private final static int MAX_MACHINE_ID = 100;<br>        private final static int MAX_SEQUENCE = 100;<br>        private final static int FAKE_MACHINE_ID = 1;<br>        private final boolean randomStart;<br>        private final SecureRandom random = new SecureRandom();<br><br>        private long lastTimeStamp = -1L;<br>        private long sequence = 0L;<br><br>        public SimpleSnowflakes(boolean randomStart) {<br>            this.randomStart = randomStart;<br>        }<br><br>        public synchronized long nextId() {<br>            long currTimeStamp = getNewTimeStamp();<br><br>            if (currTimeStamp == lastTimeStamp) {<br>                sequence = (sequence + 1) % MAX_SEQUENCE;<br>                if (sequence == 0L) {<br>                    currTimeStamp = getNextMill(lastTimeStamp);<br>                }<br>            } else {<br>                // Whether to start with a random value<br>                sequence = randomStart ? random.nextInt(MAX_SEQUENCE) : 0;<br>            }<br>            lastTimeStamp = currTimeStamp;<br>            return (currTimeStamp - START_TIMESTAMP) * MAX_MACHINE_ID * MAX_SEQUENCE<br>                    + FAKE_MACHINE_ID * MAX_SEQUENCE<br>                    + sequence;<br>        }<br><br>        private static long getNextMill(long lastTimeStamp) {<br>            long mill = getNewTimeStamp();<br>            while (mill &lt;= lastTimeStamp) {<br>                mill = getNewTimeStamp();<br>            }<br>            return mill;<br>        }<br><br>        private static long getNewTimeStamp() {<br>            return System.currentTimeMillis();<br>        }<br>    }<br>    /* Other classes */<br>}</pre><p>You can find the full code on <a href="https://gist.github.com/wcp1231/2464917504f862823dc71c2f0e5af534">gist</a>. Tests have shown that when the counter starts from 0, the chance of conflict is about 25–30% and is independent of QPS. When the counter starts from random value, the chance of conflict is reduce to 0.2–0.3%, a huge improvement!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25cde77bb8ce893435d3938363b56a84/href">https://medium.com/media/25cde77bb8ce893435d3938363b56a84/href</a></iframe><p>This is because conflict only occurs when the gap between the counter starting points is filled in each millisecond.</p><p>MongoDB ObjectId is a bit difference from my SimpleSnowflakes in that it only randomly generates machine ID, process ID and counter at startup. So a conflict will only occurs if these three random values are the same for both instances. It’s extremely low probability.</p><h4>Wrap Up</h4><p>If you want to use snowflake-like ID but without a unique machine ID, this has two suggestions:</p><ol><li>the counter starts with a random value</li><li>Increase the number of bits. The larger the random range, the lower the probability of conflict.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=05f3b53cd42c" width="1" height="1" alt=""><hr><p><a href="https://towardsdev.com/snowflake-id-in-kubernetes-05f3b53cd42c">Snowflake ID in Kubernetes</a> was originally published in <a href="https://towardsdev.com/">Towards Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Solution: All O(1) Data Structure]]></title>
            <link>https://medium.com/@wcp1231/leetcode-solution-all-o-1-data-structure-c69508658c5f?source=rss-24229f09b58c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c69508658c5f</guid>
            <category><![CDATA[datastrucutre]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <category><![CDATA[leetcode]]></category>
            <dc:creator><![CDATA[加牛不辣]]></dc:creator>
            <pubDate>Wed, 13 Mar 2024 15:47:25 GMT</pubDate>
            <atom:updated>2024-03-13T15:47:25.424Z</atom:updated>
            <content:encoded><![CDATA[<p>For me it was very good interview question, I ask this question of almost every candidate. This question is all about how to combine the use of different data structures and implement it. Doesn’t require any advanced knowledge of algorithms.</p><p>How to solve this problem? We can do it step by step.</p><p>The first step is simple, we need a hash map to hold key and its value. hash map can provide O(1) to access to keys and values, and then we can increase or decrease value.</p><p>The second step is more difficult, how to get the keys for the max and the min values. There are some common attempts:</p><ul><li>Sort by values. Doesn’t meet O(1) requirements.</li><li>Stores the value in MaxHeap. Doesn’t meet O(1) requirements.</li><li>Stores the max and the min values in two variables. It can’t find the second min key-value pair when the first one is gone.</li></ul><p>So, the question is that how to keep the key-value pair in order, and how to adjust the key-value pair to the right position in O(1) when we change its value.</p><p>The key is that inc and dec function just +1 and -1 to value. That is say when we change values, we may simply move the key-value pair to the adjacent position.</p><p>So we can stores the key-value pairs in doubly linked list which can add, remove and move element easily. How do we find the node that needs to move? We can store the nodes as values to the hash map mentioned earlier.</p><p>We are almost there, only one last corner case remains: if there are several key-value pairs with the same value, changing the value of one of them it may require moving it several times to get to the correct position. Let’s say there are m pairs with the same value, it takes O(m) to move one of them. It’s not a constant time.</p><p>How can we do? We can squeeze the keys with the same value onto a single node, so that we only need to make one move to get to the right place.</p><p>Now that the idea is there, it’s just a matter of implementing it. It’s not so easy to code the solution with three data structures combined in the interview. Here is my code:</p><pre>public class AllOne {<br><br>    static class Node {<br>        LinkedHashSet&lt;String&gt; keys;<br>        int value;<br>        Node prev;<br>        Node next;<br><br>        public Node(int value, String key) {<br>            this.value = value;<br>            keys = new LinkedHashSet&lt;&gt;();<br>            if (key != null) {<br>                keys.add(key);<br>            }<br>        }<br>    }<br><br>    private HashMap&lt;String, Node&gt; keyMap;<br>    private Node head;<br>    private Node tail;<br><br>    public AllOne() {<br>        keyMap = new HashMap&lt;&gt;();<br>        head = new Node(0, null);<br>        tail = new Node(0, null);<br>        head.next = tail;<br>        tail.prev = head;<br>    }<br><br>    public void inc(String key) {<br>        // get the node that holds this key<br>        // if not, we assumed that key is hold by head node<br>        Node node = keyMap.getOrDefault(key, head);<br>        int newValue = node.value + 1;<br><br>        // if newValue equals to next node&#39;s value<br>        // just move the key to next node<br>        if (node.next.value == newValue) {<br>            node.next.keys.add(key);<br>            keyMap.put(key, node.next);<br>            removeKeyAndNodeIfNeed(key, node);<br>            return;<br>        }<br>        // else, add new node that holding the key and newValue<br>        Node newNode = new Node(newValue, key);<br>        keyMap.put(key, newNode);<br>        addNodeToRight(node, newNode);<br>        removeKeyAndNodeIfNeed(key, node);<br>    }<br><br>    public void dec(String key) {<br>        Node node = keyMap.get(key);<br>        if (node == null) {<br>            return;<br>        }<br>        int newValue = node.value - 1;<br><br>        // if newValue equals to prev node&#39;s value<br>        // just move the key to prev node<br>        if (node.prev.value == newValue) {<br>            // if prev node is head, this means newValue is 0<br>            // delete the key<br>            if (node.prev == head) {<br>                removeKeyAndNodeIfNeed(key, node);<br>                keyMap.remove(key);<br>                return;<br>            }<br>            node.prev.keys.add(key);<br>            removeKeyAndNodeIfNeed(key, node);<br>            keyMap.put(key, node.prev);<br>            return;<br>        }<br>        // else, add new node that holding the key and newValue<br>        Node newNode = new Node(newValue, key);<br>        addNodeToRight(node.prev, newNode);<br>        removeKeyAndNodeIfNeed(key, node);<br>        keyMap.put(key, newNode);<br>    }<br><br>    public String getMaxKey() {<br>        if (tail.prev == head) {<br>            return &quot;&quot;;<br>        }<br>        return tail.prev.keys.iterator().next();<br>    }<br><br>    public String getMinKey() {<br>        if (head.next == tail) {<br>            return &quot;&quot;;<br>        }<br>        return head.next.keys.iterator().next();<br>    }<br><br>    private void addNodeToRight(Node node, Node newNode) {<br>        newNode.next = node.next;<br>        newNode.prev = node;<br>        node.next.prev = newNode;<br>        node.next = newNode;<br>    }<br><br>    private void removeKeyAndNodeIfNeed(String key, Node node) {<br>        if (head == node || tail == node) {<br>            return;<br>        }<br>        node.keys.remove(key);<br>        if (node.keys.isEmpty()) {<br>            node.prev.next = node.next;<br>            node.next.prev = node.prev;<br>        }<br>    }<br>}</pre><p>One candidate gave me another way of dealing with the several pairs with the same values, which is to use another hash map to store the first position of each value. It makes sense, but it needs a bit more refinement. It needs to store the first and the last position of each value.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c69508658c5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LeetCode Solution: Trapping Rain Water]]></title>
            <link>https://medium.com/@wcp1231/leetcode-solution-trapping-rain-water-de1381b03085?source=rss-24229f09b58c------2</link>
            <guid isPermaLink="false">https://medium.com/p/de1381b03085</guid>
            <category><![CDATA[leetcode]]></category>
            <category><![CDATA[leetcode-hard]]></category>
            <dc:creator><![CDATA[加牛不辣]]></dc:creator>
            <pubDate>Mon, 11 Mar 2024 16:30:08 GMT</pubDate>
            <atom:updated>2024-03-12T00:53:40.719Z</atom:updated>
            <content:encoded><![CDATA[<p>Problem: <a href="https://leetcode.com/problems/trapping-rain-water/">Trapping Rain Water</a></p><p>The first idea that come to me was simple: the area between highest bars must be able to trap rain water. Then we can treat the highest two bars as a whole and calculate the area between it and the third bar, and so on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NR5DFE3pjz9bpPFIXPwbWQ.png" /><figcaption>1 is the highest, 5 is the lowest</figcaption></figure><p>As shown, the area between 1 and 2 can trap water and then consider they is a whole, i.e. 1&amp;2. The area between 1&amp;2 and 3 can trap water as well, but 4 is inside of 1&amp;2, and can therefore be ignored.</p><p>Based on this idea, we can write the code:</p><pre>public class TrappingRainWater {<br><br>    /**<br>     * A class to represent a bar in the array for sorting.<br>     */<br>    static class Bar {<br>        int height;<br>        int position;<br>        Bar(int height, int position) {<br>            this.height = height;<br>            this.position = position;<br>        }<br>    }<br><br>    public int trap(int[] heights) {<br>        if (heights.length &lt;= 1) {<br>            return 0;<br>        }<br><br>        ArrayList&lt;Bar&gt; bars = new ArrayList&lt;&gt;(heights.length);<br>        for (int i = 0; i &lt; heights.length; i++) {<br>            bars.add(new Bar(heights[i], i));<br>        }<br><br>        // Sort the bars in descending order of height.<br>        // If two bars have the same height, the one with the smaller position comes first.<br>        bars.sort(Comparator.comparingInt((Bar b) -&gt; b.height)<br>                .reversed()<br>                .thenComparingInt(b -&gt; b.position));<br><br>        // Get the first two highest bars<br>        Bar left = bars.get(0);<br>        Bar right = bars.get(1);<br>        // Make sure left is the one with the smaller position<br>        if (left.position &gt; right.position) {<br>            Bar temp = left;<br>            left = right;<br>            right = temp;<br>        }<br><br>        int result = calcWaterArea(left, right, heights);<br><br>        for (int i = 2; i &lt; bars.size(); i++) {<br>            Bar current = bars.get(i);<br>            if (current.position &lt; left.position) {<br>                result += calcWaterArea(current, left, heights);<br>                left = current;<br>            } else if (current.position &gt; right.position) {<br>                result += calcWaterArea(right, current, heights);<br>                right = current;<br>            }<br>        }<br>        return result;<br>    }<br><br>    private int calcWaterArea(Bar left, Bar right, int[] heights) {<br>        // Calculate the initial area<br>        int area = Math.min(left.height, right.height) * (right.position - left.position - 1);<br><br>        // Subtract the heights of any bars that are between the left and right bars.<br>        for (int i = left.position + 1; i &lt; right.position; i++) {<br>            area -= heights[i];<br>        }<br><br>        return area;<br>    }<br>}</pre><p>Obviously, The time complexity is affected by sorting and some loops. Although it look like a nested loop, each element in actually only be accessed twice, once in the outer loop and once in the inner loop. So the time complexity is <em>O(logn) + O(n) = O(logn)</em>.</p><p>And the space complexity is clearly <em>O(n)</em>.</p><p>Yes, I know this is not the best solution, nor is the fastest or the simplest. After submit the code, I found that I had solved this problem 8 years ago with two-pointer solution, which is more simpler. Sad.</p><pre>class Solution:<br>    # @param A, a list of integers<br>    # @return an integer<br>    def trap(self, A=[]):<br>        result = 0<br>        left = 0<br>        right = len(A) - 1<br>        while left &lt; right:<br>            lower = min(A[left], A[right])<br>            if A[left] == lower:<br>                left = left + 1<br>                while left &lt; right and A[left] &lt;= lower:<br>                    result = result + (lower - A[left])<br>                    left = left + 1<br>            else:<br>                right = right - 1<br>                while left &lt; right and A[right] &lt;= lower:<br>                    result = result + (lower - A[right])<br>                    right = right - 1<br>        return result</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de1381b03085" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nostr 学习笔记]]></title>
            <link>https://medium.com/@wcp1231/nostr-%E5%AD%A6%E4%B9%A0%E7%AC%94%E8%AE%B0-8671c332efc8?source=rss-24229f09b58c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8671c332efc8</guid>
            <category><![CDATA[nostr]]></category>
            <dc:creator><![CDATA[加牛不辣]]></dc:creator>
            <pubDate>Mon, 06 Feb 2023 12:58:57 GMT</pubDate>
            <atom:updated>2023-02-06T12:58:57.344Z</atom:updated>
            <content:encoded><![CDATA[<h3>前言</h3><p>在一年多前我和朋友曾构想一个去中心化社区，但不是基于区块链实现。因为在我看来区块链的核心是不同节点达成一致性共识并生成不可修改的记录；而去中心化社区的重点是用户可以完全拥有自己的数据（创建、分发甚至编辑和删除），同时可以不经过中心服务器获取其他人的动态并互动。两者的目标并不完全相同，区块链不适合实现这种去中心化社区。</p><p>在当时的设想里，用户自己的数据完全存储在本地，并以特定的格式保存着。不联网时就是离线的微博、日记或读书笔记，可以在本地创建、编辑和删除。<br>当想要分享发布时可以将特定内容发到中继服务器供其他用户获取；同时自己也可以通过中继服务器获取到其他用户分享的内容。只要统一好数据协议和格式，就能使用不同的中继服务器发布和获取数据。</p><p>那这些中继服务器是谁来维护呢？除了爱好者无偿用爱发电之外，也可以让站长获得收益。当时的一个想法是站长可以对这些数据进行聚合整理。比如类似“编辑精选”整合某一方面的优质内容，用户可以投稿或订阅；甚至站长自己就是某一方面的大V，通过自己的中继能更好的和粉丝互动。总的来说就是中继服务器通过自身特色吸引用户，再通过打赏或广告获得收益。</p><p>但这个构造很初期、不完善。直到最近发现了 Nostr 项目，其底层逻辑和我当时的设想很像，因此这里记录一下。</p><h3>Nostr 协议</h3><p><a href="https://github.com/nostr-protocol/nostr">Nostr</a> 只是协议，通过协议规范 Client 和 Relay 的职责和行为。简单来说 Relay 只有基础的存储和分发功能，没有任何的业务逻辑；大部分的功能和扩展都基于数据格式和 Client 实现。</p><p>Client 发送和订阅事件都是请求配置的 Relay 列表，数据也存储在这些 Relay 中。因此如果两个用户设置的 Relay 列表有交集那么可以进行互动，如果 Relay 列表没有交集那这两个用户就没法互动了。因此选择合适的 Relay 挺重要的。</p><p>详情可以看 Nostr <a href="https://github.com/nostr-protocol/nips">协议文档</a>，下面选一些 Nostr 协议中有意思的部分。</p><h4>基础结构和通信协议</h4><p>Nostr 里只有一种数据结构叫 event ，格式如下：</p><pre>{<br> &quot;id&quot;: &lt;对事件数据 sha256 hash 的十六进制&gt;<br> &quot;pubkey&quot;: &lt;作者的 public key&gt;,<br> &quot;created_at&quot;: &lt;时间戳&gt;,<br> &quot;kind&quot;: &lt;事件类型&gt;,<br> &quot;tags&quot;: [&lt;附加字段，用来扩展功能&gt;],<br> &quot;content&quot;: &lt;文本内容&gt;,<br> &quot;sig&quot;: &lt;对事件数据的签名&gt;<br>}</pre><p>通信协议指的是 Client 和 Relay 之间的请求和响应。</p><p>Client 到 Relay 的请求基本有四种：<br>1. EVENT ：发布一个事件<br>2. REQ ：根据条件订阅事件<br>3. CLOSE ：关闭订阅操作<br>4. AUTH ：认证操作</p><p>而 Relay 到 Client 的响应基本有五种：<br>1. EVENT ：根据 Client 的条件返回满足的事件<br>2. NOTICE ：异常时返回错误信息<br>3. EOSE ：满足条件的事件已经全部返回<br>4. OK ：Client 的事件正常处理<br>5. AUTH ：要求 Client 进行认证</p><p>总的来说 Client 和 Relay 之间的通信方式还是很简单的，而各种功能都是基于事件中 kind 事件类型字段进行实现。</p><h4>事件类型</h4><p>当前事件类型 kind 的定义如下：</p><pre>+=============+========================<br>|    kind     |         说明            <br>+=============+========================<br>| 0           | 设置作者的基本信息        <br>+-------------+------------------------<br>| 1           | 发布一条纯文本内容        <br>+-------------+------------------------<br>| 2           | 向关注者推荐 Relay 地址   <br>+-------------+------------------------<br>| 3           | 通讯地址事件             <br>+-------------+------------------------<br>| 4           | 加密单聊信息             <br>+-------------+------------------------<br>| 5           | 删除操作                <br>+-------------+------------------------<br>| 7           | 点赞等互动               <br>+-------------+------------------------<br>| 40-49       | 群聊相关                <br>+-------------+------------------------<br>| 1000-10000  | 普通事件预留             <br>+-------------+------------------------<br>| 10000-19999 | 可重复事件预留           <br>+-------------+------------------------<br>| 20000-29999 | 临时事件预留             <br>+-------------+------------------------<br>| 22242       | Client 和 Relay 之间认证 <br>+-------------+------------------------<br>| 30000-39999 | 参数化可重复事件预留      <br>+-------------+------------------------</pre><h4>反垃圾</h4><p>垃圾用户和信息是社交媒体绕不过的问题。Nostr 的处理措施有下面这几个。</p><p>Relay 可以增加验证方式，如绑定邮箱、手机号等；也可以引入验证码等手段；甚至可以设置必须付费才能使用该 Relay。<br>Client 可以拉黑垃圾用户，如果某个 Relay 上垃圾信息过多也可以直接不使用这个 Relay。</p><p>除了上述的这几种方式，Nostr 在协议上引入了 <a href="https://github.com/nostr-protocol/nips/blob/master/13.md">NIP-13 Proof of Work</a> 工作量证明。简单来说就是在 tags 里新增 PoW 的难度和随机数字段，通过遍历随机数生成符合难度要求的 id 结果。Relay 和 Client 都可以对结果进行校验进行相应的处理，提高了生成垃圾消息的成本。</p><h4>加密消息</h4><p>kind=4 的加密消息可以实现两个人的加密单聊。具体实现很简单，事件数据的格式如下：</p><pre>{<br> // ...<br> &quot;kind&quot;: 4,<br> &quot;content&quot;: &lt;aes-256-cbc 加密内容和 vi&gt;,<br> &quot;tags&quot;: [<br>   [&quot;p&quot;, &quot;接收者的 public key&quot;],<br>   [&quot;e&quot;, &quot;回复的消息 ID，可选&quot;]<br>    ],<br> // ...<br>}</pre><p>但有一些缺陷，只加密了内容 content 部分而没有加密其他信息，因此根据 Nostr 的特性，可以知道某两个用户是否有加密聊天并且是什么频率的。为了解决这个缺陷社区提出了几种办法：<br>- <a href="https://github.com/nostr-protocol/nips/blob/nip-21-non-public-dms/21.md">NIP-21</a> 由 Relay 保证只允许用户拉取和自己有关的加密消息<br>- <a href="https://github.com/nostr-protocol/nostr/issues/69">issue-69</a> 和 <a href="https://github.com/nostr-protocol/nips/pull/56">pr-56</a> 通过密码学手段实现隐秘的单聊</p><p>与此同时，社区还有两个实现多人加密群聊的 PR：<br>- <a href="https://github.com/nostr-protocol/nips/pull/59">NIP-38</a> 通过创建群实现，功能较为完整<br>- <a href="https://github.com/nostr-protocol/nips/pull/168">NIP-48</a> 功能较为简单，基于 kind=4 加密消息功能实现，不需要新增事件类型</p><h4>徽章功能</h4><p><a href="https://github.com/nostr-protocol/nips/pull/188">NIP-52</a> 徽章功能还只是一个提案。通过新增一种事件类型实现给某个用户颁发徽章，并且可以在事件里添加一些额外的属性变成不同类型的徽章，比如添加过期字段就可以用来表示订阅会员。那么也许工作室和大V可以不需要中心服务器就可以自己运营维护会员和粉丝了。<br>TODO</p><h4>声望、评分功能</h4><p><a href="https://github.com/nostr-protocol/nips/pull/46">NIP-32</a> 声望功能也只是一个提案。通过新增一个事件类型实现给某个对象评分，比如一个商品订单、一个游戏甚至一个饭店。如果有个 Relay 对这些数据进行整合，那也许就是一个去中心化的豆瓣、大众点评了。</p><h4>举报功能</h4><p><a href="https://github.com/nostr-protocol/nips/pull/205">NIP-56</a> 举报功能也只是一个提案。通过新增一个事件类型实现举报功能，但本质上只是发布一个事件。考虑到恶意举报的情况，Client 和 Relay 做不了太多自动化的事情。感觉只能交给用户和管理员进行二次确认并屏蔽。</p><h3>一些想法</h3><p>Nostr 协议简单又易于扩展，在 tags 数组里新增所需的数据就行。所有的事件格式都是一致的，Relay 只需要提供存储和查询就能满足基本功能，功能的实现和使用体验都是 Client 负责。这样完全做到了“用户完全拥有自己的数据”。<br>还有另一个好处是，对于开发者来说开发新社交应用变得更方便了，只需要开发 Client 即可，可以直接使用现成的 Relay 实现社交互动，像服务器、数据库、域名等统统不需要。</p><p>服务器方面，现在的 Relay 逻辑很简单，只有基本的存储和查询逻辑，客户端使用体验也不好。后续也许可以在基于 Relay 搭建增强型服务器，提供优化过的高级接口提升客户的使用体验。同时如上文所说，开发特定功能的服务器可以提供诸如大众点评、什么值得买等功能，有很多想象空间。</p><p>当前 Nostr 协议里没有涉及图片、视频等内容的处理，因为图片视频比文本大太多了，Relay 处理成本太高。当前只能使用已有的图片视频存储服务，后续也许会有 Relay 提供付费功能支持图片视频的存储和分发吧。</p><p>暂时想到这么多，也许有点乱，先这样吧。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8671c332efc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[记录一个奇怪的 IllegalAccessError]]></title>
            <link>https://medium.com/@wcp1231/%E8%AE%B0%E5%BD%95%E4%B8%80%E4%B8%AA%E5%A5%87%E6%80%AA%E7%9A%84-illegalaccesserror-b050b827f6d0?source=rss-24229f09b58c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b050b827f6d0</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[spring-boot]]></category>
            <category><![CDATA[java-agent]]></category>
            <dc:creator><![CDATA[加牛不辣]]></dc:creator>
            <pubDate>Sat, 22 Feb 2020 10:33:55 GMT</pubDate>
            <atom:updated>2020-02-22T10:37:00.810Z</atom:updated>
            <content:encoded><![CDATA[<h3>奇怪的 IllegalAccessError</h3><p>我们有一个用于为 Java 服务服务添加监控的 Java Agent，简单来说就是可以在 JVM 启动时指定一个外部的 Java Agent Jar 文件，这个 Agent 会通过 <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/instrument/Instrumentation.html">Java Instrumentation API</a> 修改加载的 Class 字节码从而可以添加所需的监控逻辑。这里不得不提到一个十分好用的字节码操作库 Byte Buddy。</p><p><a href="https://bytebuddy.net/#/">Byte Buddy - runtime code generation for the Java virtual machine</a></p><p>说回问题，我们最近在添加 Spring-Boot Tomcat 线程池监控时遇到奇怪的 IllegalAccessError，简化的代码如下：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad5fe3567b80b2506e8c9e835da719a3/href">https://medium.com/media/ad5fe3567b80b2506e8c9e835da719a3/href</a></iframe><p>在测试的时候发现当执行到第 22 行的时候会报错：</p><blockquote>java.lang.IllegalAccessError: tried to access class TomcatThreadStatInterceptor$1 from class TomcatThreadStatInterceptor</blockquote><p>我们知道 22 行 new TagsGauge&lt;Number&gt;(name) { … } 会创建一个匿名内部类，也就是报错中提到的 class TomcatThreadStatInterceptor$1。但奇怪的是这个匿名内部类和 TomcatThreadStatInterceptor 在同一个包下，默认访问权限下应该是能访问到才对。</p><p>既然是访问权限的错，那么就尝试将 22 行的匿名内部类改成 Public 权限的普通内部类：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/84be7e70cb83f2ca39621113a5c94d20/href">https://medium.com/media/84be7e70cb83f2ca39621113a5c94d20/href</a></iframe><p>结果可以正常的执行，而如果将内部类的 Public 关键字去掉，就会遇到和之前匿名内部类一样的报错。那么究竟是为什么，在同一个包下的内部类无法访问呢？我查到了这篇博客：</p><p><a href="https://www.iflym.com/index.php/code/jvm-constraint-for-default-or-protected-field-between-classloaders.html">JVM对于不同classLoader加载的对象之间default或protected字段的访问限制</a></p><p>然后确认了一下确实如此：</p><ol><li>TomcatThreadStatInterceptor 由org.springframework.boot.loader.LaunchedURLClassLoader 加载</li><li>TomcatThreadStatInterceptor$TomcatTagsGauge 由sun.misc.Launcher$AppClassLoader加载</li></ol><p>为什么会是不同的 Class Loader 呢？这要从 Spring Boot 的 Class Loader 说起。</p><h3>为什么 Spring Boot 有自己的 Class Loader</h3><p>我们都知道 JVM 有三个 ClassLoader：</p><ol><li>Bootstrap Class Loader 由 C++ 编写，用于加载运行 JVM 所需要的 Java 类。</li><li>Extension Class Loader 在 JVM 启动后加载一些扩展的类，用的较少。</li><li>System Class Loader 用于加载应用服务所依赖和使用的 Java 类。</li></ol><p>那么为什么 Spring Boot 有自己的 Class Loader 呢？可以参考 Spring Boot 官方文档：</p><p><a href="https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-executable-jar-format.html">The Executable Jar Format</a></p><p>Spring Boot 提出了一种可执行的独立 Jar 文件，可以将服务自身的和所依赖的 class 文件打包成一个独立的 Jar 文件，只需要 java -jar example.jar 即可启动服务，便于部署和运行。</p><p>为了支持只需要一个独立的 Jar 文件，就需要将服务所依赖的其他 Java 库也打包到这个 Jar 文件中。因为当前 Java 官方并没有统一的嵌套 Jar 的规范，因此 Spring Boot 自己定制并实现了一个嵌套 Jar 的格式，自然也就需要自己的 Class Loader 进行加载。</p><p>我们可以用 vim 直接打开一个打包好的 Jar 文件，可以看到 Spring Boot 文档里描述的，所有文件分布在四个不同的目录：</p><pre>example.jar<br> |<br> +-META-INF<br> |  +-MANIFEST.MF<br> |<br> +-org/springframework/boot/loader<br> |  +- &lt;spring boot loader classes&gt;<br> |<br> +-BOOT-INF<br>    +-classes<br>    |  +- &lt;user classes&gt;<br>    |<br>    +-lib<br>       +- &lt;dependency jars&gt;</pre><ol><li>META-INF 目录放的是 MANIFEST.MF 文件，描述这个 Jar 包的信息。</li><li>根目录放的是 Spring Boot 框架自身的启动所需的文件</li><li>BOOT-INF/classes 放的是应用的 class 文件</li><li>BOOT-INF/lib 放的是应用的 class 文件所依赖的其他库</li></ol><p>当我们运行 java -jar example.jar 后 System Class Loader 会加载 Jar 包根目录里的 Spring Boot 框架的类，然后 Spring Boot JarLauncher 就会通过自己的 LaunchedURLClassLoader 去加载 BOOT-INF 目录下的文件，从而实现应用服务的加载和启动。</p><h3>这和 IllegalAccessError 有什么关系</h3><p>从上文我们知道，当使用 Spring Boot 时，所有的应用类和所依赖的其他库类都是由 Spring Boot 的 LaunchedURLClassLoader 进行加载。而我们为了给服务加上监控而引入的 Java Agent 则是由 System Class Loader 进行加载的。可以通过这个图看不同 Class Loader 所加载的类：</p><pre>Bootstrap Class Loader<br> +- JVM classes<br> |<br> ▲<br>Extension Class Loader<br> +- Ext JVM class<br> |<br> ▲<br>System Class Loader<br> +- Java Agent classes<br> +- Spring Boot Loader classes<br> |<br> ▲<br>Spring Boot LaunchedURLClassLoader<br> +- user&#39;s classes<br> +- dependency classes</pre><p>通过 Java Agent 修改字节码的方式，可以业务无感知的在代码里插入监控逻辑，但在给 Spring Boot 项目插入监控逻辑的过程中经常会遇到 ClassNotFoundException 异常。举个简单的 HTTP 监控的例子：</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d99812a210888aa848c8349f14fa53e/href">https://medium.com/media/3d99812a210888aa848c8349f14fa53e/href</a></iframe><p>当执行到第 14 行要将 Object 对象强转成 Request 时 JVM 需要加载 Request 类，这时 JVM 会选择由当前类也就是 TomcatInvokeInterceptor 类的 Class Loader 进行加载。</p><p>这里就会出现问题，Request 类的字节码在 BOOT-INF/lib 目录下，只会被 LaunchedURLClassLoader 找到；而 TomcatInvokeInterceptor 是 Java Agent 的类，是由 System Class Loader 进行加载。那么当 System Class Loader尝试去加载 Request 时就会找不到而抛出 ClassNotFoundException异常。</p><p>这里比较好的解决方式是让 TomcatInvokeInterceptor也由 LaunchedURLClassLoader进行加载，那么就能完全避免这个问题。</p><p>而这次遇到的IllegalAccessError 也是同样的原因造成的，虽然 TomcatThreadStatInterceptor已经是由 LaunchedURLClassLoader进行加载，但在访问匿名内部类时因为其在 LaunchedURLClassLoader中并没有被加载从而访问到上层 Class Loader 所加载的匿名内部类。</p><p>又因为匿名内部类 default 访问权限，不同 Class Loader 加载之间无法访问从而导致 IllegalAccessError错误。</p><p>显而易见，有两个解决方式：</p><ol><li>将匿名内部类改成 public 的内部类或者普通类</li><li>让 LaunchedURLClassLoader也加载这些 $1、$2 匿名内部类</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b050b827f6d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>