<?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 Idan Koch on Medium]]></title>
        <description><![CDATA[Stories by Idan Koch on Medium]]></description>
        <link>https://medium.com/@idankoch_32247?source=rss-2bd369f44b13------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*EhG6uj-7kx6CUMsY.</url>
            <title>Stories by Idan Koch on Medium</title>
            <link>https://medium.com/@idankoch_32247?source=rss-2bd369f44b13------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 08:19:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@idankoch_32247/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[3 micro tips for working with Claude Code]]></title>
            <link>https://medium.com/@idankoch_32247/3-micro-tips-for-working-with-claude-code-f5925303f8c0?source=rss-2bd369f44b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5925303f8c0</guid>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[claude-code]]></category>
            <dc:creator><![CDATA[Idan Koch]]></dc:creator>
            <pubDate>Wed, 17 Jun 2026 07:28:39 GMT</pubDate>
            <atom:updated>2026-06-17T07:28:39.849Z</atom:updated>
            <content:encoded><![CDATA[<p>Before we start, the obvious disclaimer: if you want to learn how to use Claude Code well, start with the people who actually built it.</p><p>No one can help you understand how to work with a tool better than the people who created it, and <a href="https://www.linkedin.com/in/bcherny">Boris Cherny</a> has shared a lot of great material on the subject.</p><p>For example, this is a great place to start: <a href="https://www.youtube.com/watch?v=6eBSHbLKuN0">Mastering Claude Code in 30 minutes</a></p><p>But this post is not trying to be “the ultimate Claude Code guide.”</p><p>These are just my 3 tiny favourites.</p><p>Small habits that made my day-to-day work with Claude Code smoother.</p><p>I’ve been using Claude Code quite a lot lately.</p><p>Like every new tool, at first I used it in the most basic way possible: open terminal, ask for something, wait, approve, approve again, fix something, approve again, go make coffee, come back, approve again.</p><p>After a while I started noticing that the actual coding part was not always the bottleneck. The bottleneck was me managing the session badly.</p><p>So, in the spirit of keeping things short, here are 3 micro tips that made my Claude Code workflow a bit smoother.</p><h3>1. Use /rename</h3><p>This one sounds silly, but it helps.</p><p>When you work with Claude Code often, you quickly end up with multiple sessions:</p><ul><li>one for a bug</li><li>one for a refactor</li><li>one for code review</li><li>one you started two days ago and now have no idea what it was about</li><li>one that may or may not contain the answer to life, the universe and why your test is flaky</li></ul><p>Using /rename makes the session identifiable.</p><p>For example:</p><p>/rename auth-migration-code-review</p><p>review or:</p><p>/rename m365-grafana-dashboard</p><p>Why does it matter?</p><p>Because sometimes you need to stop in the middle and resume later. Sometimes you need to jump between multiple tasks. Sometimes you realize that yesterday’s session already had all the context you need, but you named nothing and now you are scrolling through a graveyard of anonymous conversations.</p><p>Naming sessions is a tiny habit that reduces future pain.</p><p>And as we all know, future pain is the worst kind of pain, because future-you will blame current-you. And sadly, future-you will be right.</p><h3>2. Build an allowlist, but don’t go full Skynet</h3><p>As someone who grew up on Terminator 2, I do not fully trust machines running freely on my computer.</p><p>Yes, I know, very modern of me.</p><p>Claude Code can be very powerful when it can run commands, inspect files, execute tests, and make changes. But I personally don’t like running in “do whatever you want” mode. I still want guardrails. Not because I think Claude is secretly planning to destroy humanity, That line of thought is more reserved for ChatGPT 😂.</p><p>Mostly because I don’t want to be the person who accidentally creates the next <a href="https://devops.com/when-ai-goes-really-really-wrong-how-pocketos-lost-all-its-data/">PocketOS incident</a>. You know, the kind of story where everyone reads the postmortem and quietly says:</p><p>Yeah.. I would definitly never do that</p><p>And then immediately checks their own permissions. On the other hand, approving every single harmless command is annoying. The trick is to reduce the boring back and forth without removing your judgment from the equation.</p><p>You can do that through /permissions, or by updating the relevant Claude settings file. But I don’t let Claude silently change that for me. My flow is:</p><p>Look at this session and see what you asked me to allow you to do and I allowed over and over again. Recommend what should be added to your allow list, explain the risk, don&#39;t change anything yet until I approve</p><p>Then I review the suggestion and decide what to add.</p><p>Claude recommends.</p><p>I approve.</p><p>Skynet waits.</p><p>This gives you a nice middle ground. You are not blindly giving Claude the keys to the kingdom. You are asking it to analyze the actual work pattern and suggest what can be safely allowed next time.</p><p>My advice: treat the allowlist like production permissions.</p><p>Start small.</p><p>Add what is clearly safe.</p><p>Prefer read-only commands.</p><p>Be suspicious of anything that deletes, deploys, pushes, migrates, or sounds like it belongs in a postmortem.</p><h3>3. Use /branch for side quests</h3><p>Sometimes you are deep inside a session and Claude is doing something useful. For example, you are in code review mode and it keeps finding the same kind of issue:</p><ul><li>duplicated validation logic</li><li>repeated test setup</li><li>missing helper methods</li><li>unclear naming</li><li>manual checklist items you keep asking it to verify</li></ul><p>At that moment, you can continue with the main task.</p><p>But you can also branch.</p><p>/branch extract-review-skill</p><p>Then ask:</p><p>Look at the work we did in this sessionwhat repetitive or manual work can be extracted into a skill/ plugin /command so I dont have to ask again for it manually.</p><p>This is a great use of branching because it keeps the main session clean.</p><p>You don’t derail the current task.</p><p>You don’t lose the original conversation.</p><p>You just create a small side quest and ask Claude to look at the meta-work.</p><p>I found this especially useful during code review.</p><p>When Claude helps with a review, don’t only ask:</p><p>what is wrong with this PR?</p><p>Also ask:</p><p>What did I repeatdly ask you to check?</p><p>That second question is where workflow improvement hides.</p><p>Maybe you need a custom review prompt.</p><p>Maybe you need a project-specific skill.</p><p>Maybe you need a small script.</p><p>Maybe you need to update CLAUDE.md.</p><p>Maybe you just need a checklist.</p><p>The point is: don’t only use Claude to finish the current task.</p><p>Use it to improve the way you’ll do the next one.</p><h3>That’s it</h3><p>Nothing dramatic here.</p><p>No “10x developer” promise.</p><p>No AI revolution manifesto.</p><p>No “replace your team with a shell command” nonsense.</p><p>Just three small habits:</p><ol><li>Rename sessions so you can find them later.</li><li>Use allowlists carefully to reduce approval noise without going full Skynet.</li><li>Branch for side quests that improve your workflow.</li></ol><p>Small things, but they add up.</p><h3>Lastly</h3><p>Anyone who read my previous posts knows that I always add a picture of my dog, Tesha.</p><p>This will be the last one.</p><p>A few weeks ago, we had to say goodbye.</p><p>She came.</p><p>She saw.</p><p>She ate.</p><p>She was a good dog.</p><p>Bye Tesha ❤️</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/989/1*OnoWiF3F0F3EKvji4ZQCCg.jpeg" /><figcaption>Goodbye Tesha</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5925303f8c0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The ultimate checklist to becoming a development team leader]]></title>
            <link>https://medium.com/@idankoch_32247/the-ultimate-checklist-to-becoming-a-development-team-leader-77faf921208d?source=rss-2bd369f44b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/77faf921208d</guid>
            <category><![CDATA[team-leader]]></category>
            <category><![CDATA[managment-software]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[growth]]></category>
            <category><![CDATA[software-management-tools]]></category>
            <dc:creator><![CDATA[Idan Koch]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 21:49:46 GMT</pubDate>
            <atom:updated>2024-06-27T21:49:46.393Z</atom:updated>
            <content:encoded><![CDATA[<p>My name is Idan Koch, I’ve been working in high tech in various roles for over 2 decades. During this period I had the great pleasure of working with immense talents and great people. Over the years I took an active part in the team members growth process and was an observer of talented developers making the shift to different positions. The most common use case I encountered were developers moving from individual contributors to team leader roles. Usually the question is <strong>“what do I need to do to show I’m ready?”</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*5WzHrxdSIxNzpcE-iXtn8A.png" /><figcaption>Tesha leading by example</figcaption></figure><p>While navigating your career, sometimes it is unclear what needs to be done to advance to your next role, may it be as a technical leader, team leader, group management or anything else. There isn’t always a clear guideline in companies about what needs to be achieved to get from A to B. However, for the shift from IC to TL over the years I made a simple checklist for any developer wanting to make this shift to go over. This list is based on my experience, not all items are a must, some can be ruled out depending on previous experience or company’s expectation of the role. However, I will say from my extensive experience in this matter this list is pretty solid across the board.</p><ol><li><strong>Conquer your domain</strong></li></ol><p>Becoming a TL will require you to represent your team in various technical and design meetings, answering questions from inside the team and outside of it and either be responsible or assist in production incidents. In order to be up to the task you should do the following:</p><p><em>1.1. Deliver like a motherf#%&amp;r</em></p><p>You can read documents, watch recorded sessions and be in meetings. For me there is no substitute for writing as much code in as many services/business flows as you can. Even if you become a TL in a different group/company this skill of diving head first into various chunks of code helps you understand the domain faster, learn your stack faster and understand the pain points of development. Sometimes your team’s responsibilities are very extensive with many services, so it is hard to cover everything. My advice would be to try to do a bunch of small tasks around those services. Small tasks lead to quick wins which is always a great feeling to check off tasks, but more importantly give you a taste of everything. You will cover different flows, different solution considerations, different SLAs and different technologies.</p><p><em>1.2. Become a production hero</em></p><p>This section depends on your job description, some developers are detached from production. However, if you are lucky enough to have production responsibility, then as a technical leader you will either be in the driver’s seat when shit hits the fan or provide backup to your colleagues. Handling production incidents will help you grow. A few key points about production incident management:</p><p><em>Tools of the trade</em> — learning tools such as: profiling, log tracing, testing in production, mitigating different issues with different solutions will give you understanding not only how to solve issues, but mainly will give you a way to think about problem solving.</p><p><em>Stress reduction — </em>There are developers that are inherently calm under any production pressure by default, it is OK if your not. One way to lower your production anxiety is exposing yourself to it as much as possible. The only way to learn is to jump in. You can start by “shadowing” the oncall person and assume incident management gradually over time. After a while you just get used to it.</p><p><em>Bug hunts — </em>You don’t need to wait for an incident to happen, you can be proactive to find issues. At times incidents fly under the radar and go unnoticed, could be missing alerts or old service that dont have new requirements and are neglected. In my group we do periodic bug hunts where as part of your oncall you select a service and deep dive it and present it to the rest of the group. In the bug hunt we start with service spotlight where you discuss the service responsibility product concerns showing examples of user flows in UI. After that we take a look at the service technically. Examining resilience issues, think about fallbacks in case of failures, check which health tests are running, find cutting cost opportunities, go over exceptions see if there is anything interesting to handle, make sure you have all the dashboards and alerts you expect there to be, go over past post mortems and most importantly create action items and create backlog of items that will improve the quality of the service.</p><p><em>1.3. providing support</em></p><p>Often your team receives inquiries from other teams. The questions may vary from API questions, to how flows work, production assistance and more. This usually leads to deep diving into old code and asking around why things are like they are. Answering questions will help you establish your knowledge on the team’s domain outside of your daily tasks. Additionally, answering as many questions as you can will help you become a focal point of knowledge.</p><p><strong>2. Onboarding</strong></p><p>Leading others will require you to juggle between your tasks and helping someone else with theirs, having constant context switches and knowing how to handle them. For example, a new team member turns to you every 2 minutes with a question. You can answer every question immediately, but you might not get anything done. An alternative would be to say “Let’s set a 1 hour meeting after lunch. I want to put the final touches on my PR so I can focus on your questions”. Fortheremore, You will learn the subtle art of knowing when to let others “struggle” a bit so they can learn how to learn and when to dive in and help. So how do you practice those skills before becoming a TL?</p><p>I personally find it extremely useful to have the last person that has boarded on the team to be the “buddy” of a new team member. Helping them get a handle on things, understand key personnel to turn to, what are the processes used in the company/team, help them with coding style, lead them to the “right” place to eat lunch … all questions big and small (lunch is by far the biggest). This phase is great since it first tests your own knowledge. Best way to know that you actually know what you are talking about is by explaining it to someone else. You will find gaps in information, that is OK, it is even great. Most importantly, it is a hands on experience in leading someone else, this will help you understand if you actually like it or not.</p><p><strong>3. Big tasks</strong></p><p>From time to time you will get a task that is not a quick win. Handling big tasks will require months of development, Integrations with other teams and setting expectations with the product team. As a team leader you will have to not only know how to do this yourself but also help others. When you start your development career you start this journey with the help of your manager while focusing on:</p><p><em>requirements </em>— Collect all the requirements and give feedback, ask hard questions (like this be phase 2?). Understand current flows how and why they are implemented as they are? Make sure you know the impact of this new feature, how will this make the life of our users better?</p><p><em>Design — </em>So you collected all requirements, now you need to meet them. You need to have a design that addresses all requirements (usually there is more than one). Design reviews with all technical parties are needed to get feedback and create action items to flow up. This process can have several iterations, at times even going back to the requirement phase. It is your job to make those iterations as short as possible. You will find “shortcuts” like getting feedback from specific technical focal points before the review to raise concerns faster or even just creating a slack channel dedicated to the feature which allows you to share information and questions to a wider audience.</p><p><em>Dependencies — </em>Even though it is part of the design part it deserves its own section. Often than not you depend on other teams. You need to understand their domain to some extent. You need to understand their challenges, is what you are requesting of them is even feasible with their current system. You need to understand how long it will take them to hold up their end. Lastly, you need to understand where their priority is. Can they meet you at the integration points? Do you need to raise a red flag when there is risk of non commitment from other teams? Know who to ask for help to get priority from other teams. Maybe code contribute if needed.</p><p><em>Have a plan — </em>Break everything down to small tasks. Mark dependencies between tasks, which task blocks other tasks. Mark tasks that can be done in parallel (in case you get extra hands to help you). Set exact timelines (as much as possible) for deliverable and integration.</p><p>Time estimation is always tricky, the process of time estimations, at times, teaches you not to be too optimistic, sounds depressing but actually it is key to free yourself from future stress. You will need to remember when you are oncall, when there is a company meetup, when your kid’s soccer game is held, holidays or any other obligation you might have will have an impact on delivery dates. If possible leave some room to breathe, big tasks are marathons. There are unexpected events happening along the way, context switches will happen. My rule of thumb is if you don’t know how to estimate the unknown make sure you have an additional 20% of time. Usually extra time needed for integrations, production testing, bugs or those wonderful days when the build is broken and you need to spend a day figuring out why. So for example: if the task takes a month to complete probably more realistically you will need an extra week for it.</p><p><em>periodic checks — </em>Periodic check meetings with your manager and peers will help you to make sure you are on track. Sometimes when we are in the thick of things we lose sight of the big picture. We need to zoom out of the task at hand and look at the whole board.</p><p><strong>4. Big tasks — you are on your own</strong></p><p>This time do it yourself. obviously consult with your managers and peers but you lead the way. prepare the design document, talk to other companies, give the estimate, set the design meeting, basically do anything and everything to move things along.</p><p><strong>5. Big tasks — lead others</strong></p><p>This is not a must, however, in my opinion a clear sign of readiness to be a TL. When you have a big task and you need to help lead other teams technically, product, timelines. This gives you a taste of being in other people’s shoes, understanding their challenges and helping them overcome them to get to the greater goal.</p><p><strong>6. Meetings — optional step</strong></p><p>Big part of being a TL is being in meetings. Design reviews, technical consultations, brain storms, work process reviews. Even if you are not lecturing in a big conference you will find yourself standing in front of other managers and other big shots in your company while you explain technical issues, design concerns, lead discussions and answer to feedback. You will have to organize your thoughts in a clear way so you can deliver your message properly. Your managers will gain confidence in you when they actually see you in this setting. I will admit this step is a bit more mercurial, it’s not always a must and at times can be on the job training. However, if you get a chance to try it, it will help you progress and grow. Additionally, if you see someone else that holds complex meeting and navigate through the sea of challenges and ego to the promise land of action items — then ask yourself how did they achieve this? What preparation was needed? More specifically, if you see someone that you want to “model” or take “aspects” of their professional skills and adapt them, ask them questions. Maybe you will get lucky to get them to be your mentor. Mentorship is an awesome way to progress your process by having someone external follow challenges, give you advice and impartial feedback on your progression.</p><p><strong>In Summary:</strong></p><p>When a team member wants to journey and transition from developer to team lead I would reflect them my expectations:</p><ol><li>Deliver as much as possible.</li><li>Be on top of all production issues and support questions.</li><li>Get a taste by onboarding others.</li><li>Take on big tasks first together with your TL, then lead the way alone.</li><li>If possible, lead “important” meetings.</li></ol><p>Feel free to hit me up in the comments section, I would love to get feedback on what you think about this list or just learn what are the processes you have installed to help teammates grow to technical leadership positions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77faf921208d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tales from Elasticsearch upgrade]]></title>
            <link>https://medium.com/@idankoch_32247/tales-from-elasticsearch-upgrade-469624034b0d?source=rss-2bd369f44b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/469624034b0d</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Idan Koch]]></dc:creator>
            <pubDate>Tue, 03 May 2022 06:16:59 GMT</pubDate>
            <atom:updated>2022-05-10T08:00:07.566Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m a team lead server infra core at Wix and our team maintains several services in production. Some services are legacy some new. One of our legacy services performs searches over the Elasticsearch cluster. Recently we tackled upgrading Elastic from v6 to v7 (or newer) due to the EOL of v6. If you worked for a few years in the industry you probably know what it is like to have a legacy service that you maintain, and add features to it but never really deep dive into it. To start the process of an upgrade there was a lot of “catchup” regarding our Elasticsearch knowledge, my team and I needed to close the gap while delivering to production. In the process, we took an online course, read a lot of documentation, and consulted with experts across Wix and outside of it. Even though our work is not completed yet, here are some of the lessons learned from this process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QaCa-m7GZ2SwKfTUTax8EA.png" /><figcaption>Tesha retrospective look</figcaption></figure><p><em>System parameters:</em></p><ul><li>We have a synchronous blocking server that calls Elasticsearch v6</li><li>Max read requests per minute (RPM) 40K</li><li>Max Writes RPM 60K</li><li>The document is an aggregation of Multiple Data Sources</li><li>We have more than 500M documents spread on 7 nodes with 20 shards and one replica</li><li>Schema is <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-mapping.html">dynamic</a></li><li>Index size including replica — ~780GB per node (5.6TB including replica)</li><li>Our query spans cross tenants. Meaning, we hit all the shards in every query</li></ul><p>What have we learned?</p><ol><li><strong>Raw data vs Preprocessed data — </strong>our old index was comprised of data collection from several data sources and aggregation into a big document using<a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-mapping.html"> dynamic mapping</a>. Using dynamic mapping made it easy to add new fields fast. Additionally, The raw data was saved as is and it made it easier to expose new fields based on this data to clients without the need to reindex for every new requirement. The downside was that all raw data was saved and document sizes got to be pretty big. This resulted in timeouts when deserializing large page sizes with large documents. In order to mitigate the timeout issue, we created a smaller index with a strict schema. We only indexed what we exposed to our clients. This resulted in smaller documents and a faster deserialization time. Additionally, We saw a huge decrease in our index size (from 2.8Tb without replica to 1TB) which cut costs a bit. The downside of a strict schema is you need to migrate all documents for every newly added field but you keep a clear view of what you need.</li><li><strong>Page size limits</strong> — In general you should be mindful when creating a listing or any bulk API and create a low page size limit as much as possible. Otherwise, you will find yourself with several issues that impact performance, large memory footprint, or failures. Lowering page sizes entails communication to other teams about the change, Having other teams prioritize this change, and keeping tabs to make sure they are all done. So it’s best to start with a low page size limit and increase over time.</li><li><strong>Verifying changes </strong>— one of the drawbacks of making changes to your schema is that you need to make sure that the results will remain the same. You want to test actual queries from production without taking up too many resources from your system and definitely without SLA degradation. The way we verified those changes was by running a separate thread pool that would take samples of queries in the background. That thread will run against the newer version of Elastic with the same query and compare results. Going over the logs of such a comparison allowed us to find a bug that would have taken us some time to discover.</li><li><strong>Number of shards — </strong>We got a recommendation from DBAs that shards are too big and that shard size too big should not exceed 50Gb per shard (which correlates with Elastic <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/size-your-shards.html#:~:text=There%20are%20no%20hard%20limits,Search%20and%20similar%20use%20cases.">recommendation</a>). We decided to increase the number of shards from 20 to 170 (calculation of each shard being under 50Gb and with room to grow), under the assumption there wouldn’t be any performance impact. However, Our queries (even the basic ones) hit all shards (we query by several fields which collect documents from several shards). The use of routing would not help for the same reason, we query across several tenants. As a result, we saw an increase in response time. In hindsight, this makes sense since you need to aggregate from more shards which result in more IO. With the decrease in index size (see the previous item) we landed on 30 shards spread on 7 nodes. However, this experience leads to the next lesson learned and the most important one.</li><li><strong>Number of changes — </strong>When you start a project, especially one with many unknown variables, it’s best to prioritize changes. You should list all wishlist changes and set what is more important to you….. Sounds trivial, right? In our upgrade process, every change in cluster configuration requires the migration of 500M documents. The data is not static and needs to be retrieved from several data sources. Each iteration of migration can take a lot of time (will touch on that in the next item). It is best to allow yourself room to fail with minimal parameter changes. In our example: changing the document to be preprocessed data instead of raw data was a must (it led to failures in production). But changing cluster config (number of shards) should have been postponed for a later iteration (after going live with the upgraded cluster). This set us back a migration cycle or two.</li><li><strong>Indexing — </strong>My team holds many services with a large amount of data and high RPM (some services&#39; RPM are in the millions). Migrating large amounts of data is our bread and butter. However, even in this migration, there were a few details to learn from. As I stated before we hold 500M documents collected from several data sources. We have an internal tool that allows you to trigger migration based on a key (in our case document Id). The migration tool calls an RPC/gRPC endpoint and returns the result (failed/success/skip). Our endpoint in turn calls several services at Wix to collect up-to-date data for the index. The strength of the migration tool is the visualization of the process. You can see how long it takes and cap the RPM if needed. When we started the migration process we saw that the rate of migration would have taken us weeks if not months. The bottleneck of our migration was the amount of RPM that we can call external services and the response time of each endpoint. We halted the process and did some homework. Using table views of other teams’ data we saw that calling all endpoints for every document is redundant. We saw 2 services that resulted in extremely high response times. Fortunately for us, the data those services provided were relevant to less than 10 percent of the documents. We broke down the data collection into several indexing efforts which allowed us to “hit” most of the data at a relatively higher speed. The data from the slow services were later added to a smaller portion of the documents.</li><li><strong>Using nested fields — </strong>Our document contains nested objects which require querying its fields with AND and OR conditions. However, the way Elastic indexes nested objects is by flattening the fields. As a result search queries with AND conditions can end up with the wrong result. The perfect example is elastic <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html">documentation</a>. On that same documentation page is the solution (or so we thought). Marking certain fields as nested should provide us with the needed functionality. However, when reaching production we got an insane amount of IOPS and degradation in performance. Why? each nested field item creates a separate doc. For write-intensive usage of Elastic (like us with 40k RPM writes), this results in loads of merges. If you ask yourselves what is merge? I think it is best explained in the following in Elastic <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/index-modules-merge.html">documentation</a> or in <a href="https://medium.com/@nschsravanthi">Sravanthi Naraharisetti</a> great summarized <a href="https://medium.com/@nschsravanthi/elasticsearch-document-life-cycle-b962a8dedb24">post</a>. The general concept is once you update a document it will be marked for deletion and when segmentation merges occur there will be more deletions of documents. In our index, we have a field that is a sequence of complex objects. That sequence can contain over a hundred items. For ease of calculation purposes: if you have 1 document with the nested field of the length of 100, you will have 101 documents. This results in crazy IOPS (Elastic is busy deleting documents) and degradation in search read performance. We delayed our solution for now (see item 5 on this list — number of changes). But we have discussed “fuse” all the relevant fields in one searchable field in the future to support And and Or queries.</li><li><strong>Cache — </strong>In our flow user’s expected behavior is to query their data infrequently (no more than a few calls in the span of a few minutes). Furthermore, The amount of documents that the user has is pretty capped at a reasonable rate. From time to time we saw an increasing amount of IOPS with long queries. Looking at our slow query log we saw that we had some users with an abnormal amount of traffic spikes. After going through the logs we saw we were “attacked” by our automation users. Those users had an abnormal amount of documents. Adding <a href="https://www.elastic.co/guide/en/elasticsearch/reference/current/query-cache.html">cache config</a> relieved the performance issue considerably. However, as I said in my opening comments, the service calling the Elasticsearch cluster is a legacy service that is implemented in a blocking fashion. This means that slow response from external calls will exhaust all threads in service pretty quickly. Even with autoscaling defined, automation traffic was hitting spikes very fast (faster than autoscaler detection of RPM spike). Those RPM spikes caused our health tests to not run (there were no threads left to run health tests), essentially killing our service in production. We were able to get to the root of the problem with the relevant automation developers. Still, in order to protect ourselves in the future, we need to rewrite the service to be asynchronous. Additionally, our group is developing a general rate limiter that will prevent abuse of the system in general.</li><li><strong>Cold starts — </strong>Every time we opened the feature toggle to use the new version of elastic we saw “insane” response times for a few minutes then they died down. Additionally every data center traffic switch this issue returned again. This pointed to the fact that we need a warmup process for Elastic. We implemented that every pod that goes up will first query Elastic 5 times with a general query. The inactive DC has minimal pods to save cost. However, When traffic switches auto-scale kicks in which warms up elastic pretty quietly before actual traffic reaches the DC</li><li><strong>Work locally — </strong>Installing <a href="https://youtu.be/ARqtUizWkvg">Elasticsearch</a> on your computer and using <a href="https://youtu.be/psNH33pcGBo">Kibana</a> is a great way to cut down one development lifecycle. You can test schema changes/queries/commands easily and without the stress of changing production on the fly.</li><li><strong>Course</strong> — Udemy has a great <a href="https://www.udemy.com/course/elasticsearch-complete-guide/?couponCode=CEPROMO202202">course</a> … highly recommended as a starting point</li><li><strong>Ask a lot of questions </strong>— I feel I’m lucky to be working at a place like Wix. our structure of companies and guilds allows our group to move fast as a startup and to enjoy the resources of a big company. One of the major perks is that our backend guild has an incredible amount of seasoned developers with tons of experience. So you would find more often than not an answer to any technical question in one of our slack channels.</li><li><strong>Working as a team</strong> — When more than one person works on such a project you need to divide tasks properly and find the tasks that “intersect” or have dependencies between them. In our team, I started developing a framework. By the time other team members joined the effort the tasks were divided into writing tasks and reading tasks. When read and write tasks “collided” team members just sat together in pair programming. But the crucial thing is communication. I’m not a big fan of a rigid structure of management with strict processes. But daily sync (30 minutes each morning) helped to raise a lot of issues fast and allowed us to resolve them quickly. Not to mention during COVID-19 it’s just nice to see your teammates for a morning coffee, even if it’s through zoom.</li></ol><p><strong>Final thoughts:</strong></p><p>As I mentioned in the beginning I’m not an expert on Elasticsearch. There are some more changes we would like to do, mainly changing the schema to make hits more localized to a single shard (or at least not all of the shards). Going through the upgrade process, and talking to other developers with more experience with Elastic and even paid professionals it seems that the road to production with Elastic takes time and tunning cycles. There appears to be no rule of thumb, every index and its set of queries need to be addressed differently.</p><p>Lastly, we are still faced with a conundrum of crazy IOPS spikes, even though traffic is the same as in our v6 Elastic. We suspect some cluster configuration is missing. Once we figure it out I will update this post (or write a new one). If you ever encountered such behavior when upgrading to v7, feel free to hit me up…. I’m Hiring :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=469624034b0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Future.await(s) for no one]]></title>
            <link>https://medium.com/@idankoch_32247/the-future-await-s-for-no-one-652ed333f752?source=rss-2bd369f44b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/652ed333f752</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[future]]></category>
            <category><![CDATA[outofmemoryerror]]></category>
            <dc:creator><![CDATA[Idan Koch]]></dc:creator>
            <pubDate>Sun, 17 Nov 2019 07:02:39 GMT</pubDate>
            <atom:updated>2019-11-17T07:02:39.816Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever wondered what happens to a scala <em>Future</em> if you don’t wait for it to resolve? This post is a lesson learned from a production issue that happened to me a while ago while writing a new service. Long story short, not waiting for a <a href="https://docs.scala-lang.org/overviews/core/futures.html"><em>Future</em></a> to resolve<em> </em>can lead to an<em> </em><a href="https://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html"><em>OutOfMemoryError</em></a><em>.</em> <em>Side Note:</em> If you read any of my previous <a href="https://medium.com/@idankoch_32247">posts</a> you know I like to keep it short… this post will be no different.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jrt-sDo7jv4qsNesMcmGuA.jpeg" /></figure><p>To recreate the issue, we will create a simplified example. Let’s start by defining a small program that performs a simple quick operation called <em>performAction</em>. All that <em>performAction</em> does is print “Hello world”. <em>performAction</em> is wrapped with a <em>Future</em> and it is called time and time again.<br>Furthermore, we define a thread pool of core size 2 and max size 10 that will handle the future execution.</p><pre><strong>import </strong>java.util.concurrent._<br><strong>import </strong>scala.concurrent.ExecutionContext<br><strong>import </strong>scala.concurrent.Future</pre><pre><strong>val </strong>executor = <strong>new </strong>ThreadPoolExecutor(<br>  2, //corePoolSize<br>  10, //maxPoolSize<br>  100000,<br>  TimeUnit.<em>MILLISECONDS</em>,<br>  <strong>new </strong>LinkedBlockingQueue[Runnable]()<br>)</pre><pre><strong>def </strong>performAction()(<strong>implicit </strong>ec: ExecutionContext) =<br>  <em>Future </em>{<br>    <em>println</em>(<strong>&quot;Hello world&quot;</strong>)<em><br>  </em>}</pre><pre><strong>implicit val </strong>ec = ExecutionContext.<em>fromExecutor</em>(executor)</pre><pre><strong>while </strong>(<strong>true</strong>) {<br>  performAction()<em><br></em>}</pre><p>When running the code in REPL the console starts filling up with “Hello world” prints. After a short period an <em>OutOfMemoryError</em> is thrown, But why?</p><p>Console printout example:</p><pre>Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread &quot;main&quot;</pre><pre>Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread &quot;pool-1-thread-1&quot;</pre><pre>Exception: java.lang.OutOfMemoryError thrown from the UncaughtExceptionHandler in thread &quot;pool-1-thread-2&quot;</pre><p><em>Side Note</em>: you can speed up the process by lowing the scala REPL memory setting, like so:</p><pre>env JAVA_OPTS=<strong>&quot;-Xms100m -Xmx100m -XX:+PrintGCDetails -Xloggc:gclog.log&quot; </strong>scala</pre><p>It seems that only 2 threads are running even though the maximum thread pool size is 10. Adding debug lines confirms this:</p><pre><em>println</em>(<strong>s&quot;heapFreeSize: $</strong>{Runtime.<em>getRuntime</em>.freeMemory}<strong>&quot;</strong>)<br><em>println</em>(<strong>s&quot;getPoolSize: $</strong>{executor.getPoolSize}<strong>&quot;</strong>)<br><em>println</em>(<strong>s&quot;getQueueSize: $</strong>{executor.getQueue.size()}<strong>&quot;</strong>)</pre><pre>getQueueSize: 666698<br>heapFreeSize: 1092544<br>getPoolSize: 2<br>getQueueSize: 667516<br>heapFreeSize: 990720<br>getPoolSize: 2<br>getQueueSize: 667793<br>heapFreeSize: 990720<br>getPoolSize: 2<br>getQueueSize: 668054<br>heapFreeSize: 886224<br>getPoolSize: 2</pre><p>The printout indicates that free memory decreases over time, no big whop there. The executor queue size starts growing and growing as a result of submitting the <em>Future</em> tasks to the queue. This is a direct result of defining <em>performAction</em> as asynchronous. The function doesn’t wait for the print to occur and new tasks are created faster than the threads in the thread pool can handle. This explains the <em>OutOfMemoryError</em>,<em> </em>but why only 2 threads are used? The answer is found in <a href="https://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ThreadPoolExecutor.html">ThreadPoolExecutor.java</a> documentation:</p><pre>When a new<strong> </strong>task is submitted in method {@link #execute(Runnable)},<br>and fewer than corePoolSize threads are running, a new<strong> </strong>thread is<br>  created to handle the request, even if<strong> </strong>other worker threads are<br>  idle. If there are more than corePoolSize but less than<br>maximumPoolSize threads running, <strong>a new thread will be created only<br>if the queue is full</strong>. By setting corePoolSize and maximumPoolSize<br>the same, you create a fixed-size thread pool. By setting<br>  maximumPoolSize to an essentially unbounded value such as {@code<br>  Integer.<em>MAX_VALUE</em>}, you allow the pool to accommodate an arbitrary<br>  number of concurrent tasks. Most typically, core and maximum pool<br>  sizes are set only upon construction, but they may also be changed<br>  dynamically using {@link #setCorePoolSize} and {@link<br>  #setMaximumPoolSize}.</pre><p>Meaning, the use of <em>LinkedBlockingQueue </em>default queue size (which is Integer.<strong><em>MAX_VALUE</em></strong>)<strong><em> </em></strong>leads to new threads not be created (you will run out of memory before the queue is full). Defining core pool size to be equal to the max pool size is advised (worst case you will have some idle threads). Unfortunately, this setting will just delay the problem, after awhile all threads being used will not be able to handle the pace. Additionally, throwing more threads at the problem won’t help, since your machine has its limits too (each thread created takes up memory). Another solution would be to cap the queue size. However, this leads to a new problem. After a while tasks will get rejected once the queue is full and you will start seeing <em>RejectedExecutionException </em>like this:</p><pre>java.util.concurrent.RejectedExecutionException: Task scala.concurrent.impl.CallbackRunnable@27605b87 rejected from java.util.concurrent.ThreadPoolExecutor@67b8d45[Running, pool size = 1000, active threads = 1, queued tasks = 0, completed tasks = 1244]<br>at <br>java.base/java.util.concurrent.ThreadPoolExecutor$AbortPolicy.rejectedExecution(ThreadPoolExecutor.java:2055)<br>at java.base/java.util.concurrent.ThreadPoolExecutor.reject(ThreadPoolExecutor.java:825)<br>at java.base/java.util.concurrent.ThreadPoolExecutor.execute(ThreadPoolExecutor.java:1355)<br>at scala.concurrent.impl.ExecutionContextImpl.execute(ExecutionContextImpl.scala:20)<br>at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68)<br>at scala.concurrent.impl.Promise$KeptPromise$Kept.onComplete(Promise.scala:368)<br>at scala.concurrent.impl.Promise$KeptPromise$Kept.onComplete$(Promise.scala:367)<br>at scala.concurrent.impl.Promise$KeptPromise$Successful.onComplete(Promise.scala:375)<br>at scala.concurrent.impl.Promise.transform(Promise.scala:29)<br>at scala.concurrent.impl.Promise.transform$(Promise.scala:27)<br>at scala.concurrent.impl.Promise$KeptPromise$Successful.transform(Promise.scala:375)<br>at scala.concurrent.Future.map(Future.scala:288)<br>at scala.concurrent.Future.map$(Future.scala:288)<br>at scala.concurrent.impl.Promise$KeptPromise$Successful.map(Promise.scala:375)</pre><p>Which leads to the obvious of waiting for the future to resolve:</p><pre>Await.<em>result</em>(performAction(), 1.seconds)</pre><p>After that, if you still are unable to handle the load on your server then cheer up you just wrote a piece of code that is widely used ….so just sit back and scale-up.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=652ed333f752" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[So you want to develop an IntelliJ plugin]]></title>
            <link>https://medium.com/wix-engineering/so-you-want-to-develop-an-intellij-plugin-f552f6309be2?source=rss-2bd369f44b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/f552f6309be2</guid>
            <category><![CDATA[plugins]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[intellij]]></category>
            <category><![CDATA[bazel]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Idan Koch]]></dc:creator>
            <pubDate>Thu, 10 Jan 2019 16:35:19 GMT</pubDate>
            <atom:updated>2019-01-10T16:35:19.795Z</atom:updated>
            <content:encoded><![CDATA[<p><em>WixEng</em> is moving from Maven to <a href="https://bazel.build/"><em>Bazel</em></a>, I joined the <em>Bazel</em> tools task force and I had the opportunity to work on <a href="https://www.jetbrains.com/idea/"><em>IntelliJ</em></a> Bazel plugin. Here is a bit of what I learned along the way. Hopefully, this post will help you kickstart future development efforts.</p><p>If I could give one piece of advice it would be this: “<em>Before crafting a solution, it is best to try to understand the tools that are your disposal</em>”. I found that doing some reverse engineering is best. Look at other known functionality in <em>IntelliJ</em> and try to find one that resembles what you need and try to understand it using <a href="https://www.jetbrains.org/intellij/sdk/docs/welcome.html">documentation</a> and examples from <a href="https://github.com/JetBrains/intellij-sdk-docs">SDK project</a> or other plugins (example: <a href="https://github.com/JetBrains/intellij-scala">Scala Plugin</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/373/1*TcZTKpc85EG-Vfu9s9R6qA.png" /><figcaption>Because every blog post needs a picture</figcaption></figure><p><strong>Where do I begin?</strong></p><p>Try out the <em>JetBrains </em><a href="https://www.jetbrains.org/intellij/sdk/docs/basics/getting_started.html">getting started</a> example! Their <em>“Hello World”</em> plugin example will allow you to experiment and expand functionality, help you understand how to setup your plugin components, figure out the lifecycle of the components you intend to use and most importantly let you run and debug your code for the first time.</p><p>You will need to setup <em>IntelliJ</em> SDK to compile and use classes… well …from <em>IntelliJ</em> SDK,</p><p>In order to do so:</p><ol><li>Open project settings</li><li>press +</li><li>Choose “IntelliJ Platform Plugin SDK”</li><li>Here you can either point to your current <em>IntelliJ</em> instance or download community edition. Either way point it to the Contents folder. Example: /Applications/IntelliJ IDEA CE.app/Contents, it will look something like this:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HFrR_yjCDRIMnYwe" /></figure><p><strong>My project Example:</strong></p><p>What did I set to accomplish?</p><p>1) When building/syncing projects using <a href="https://docs.bazel.build/versions/master/bazel-overview.html">Bazel</a> show errors on imports (Red squiggly lines over import) when their dependencies are not included in the relevant build files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*Pvd1wheHNxAP_NZyJSmrDA.png" /></figure><p>2) Add quick fix help if missing dependency is in the same repo</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/489/1*DT3lfllj75j9X6ZlQCEeMA.png" /></figure><p>3) When pressing “Add dependency to build file” will add dependency to the relevant build file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*zEtBz60reccpMrsR" /></figure><p><strong>My solution:</strong></p><ol><li>Create a service that will collect all import issues.</li><li>Create an annotator that checks if a certain import line has an open issue highlights the problem.</li><li>Add dependency to build file using PSI elements tools.</li></ol><p><strong>Part 1 — Define a service that will manage import issues</strong></p><p><em>What is a </em><a href="https://www.jetbrains.org/intellij/sdk/docs/basics/plugin_structure/plugin_services.html"><em>service</em></a><em>?</em></p><p>Simply put, it is a development unit which holds your logic. Like every component in <em>IntelliJ</em> plugin you need to configure your component in plugin.xml</p><pre><strong>&lt;extensions defaultExtensionNs=&quot;com.intellij&quot;&gt;<br></strong>  <em>&lt;!-- Add your extensions here --&gt;<br></em><strong><em>  </em>&lt;applicationService    serviceInterface=&quot;</strong>com.google.idea.blaze.base.ui.problems.ImportProblemContainerService<strong>&quot; serviceImplementation=&quot;</strong>com.google.idea.blaze.base.ui.problems.ImportProblemContainerService<strong>&quot;&gt;<br>  &lt;/applicationService&gt;<br>&lt;/extensions&gt;</strong></pre><p><em>How do I get an instance of the service?</em></p><p>Accessing components is done using static method of relevant manager. For service retrieval use <em>ServiceManager.</em></p><pre>ServiceManager.<em>getService</em>(ImportProblemContainerService.<strong>class</strong>);</pre><p><strong>Part 2 — Highlight the import line</strong></p><p>By using <a href="https://www.jetbrains.org/intellij/sdk/docs/tutorials/custom_language_support/annotator.html">annotators</a> I was able to go over a file’s PSI elements and single out import statements. For every import statement I check if there is an open issue exist for it and if so add error indication (Red squiggly line).</p><p><em>What are </em><a href="https://www.jetbrains.org/intellij/sdk/docs/basics/architectural_overview/psi_elements.html"><em>PSI elements</em></a><em>?</em></p><p>Basically it is a tree structure of the files you are working on. The element holds metadata and operations needed to change the files. In order to look at PSI structure of a file you can use <em>IntelliJ</em> internal tools.</p><p><em>Internal Tools </em><a href="https://rider-support.jetbrains.com/hc/en-us/articles/207327910-How-to-run-JetBrains-Rider-in-Internal-Mode"><em>Setup</em></a></p><ol><li>Go to Help</li><li>Edit Custom Properties</li><li>If a file doesn’t already exist add it</li><li>Insert the following line: <strong>idea.is.internal</strong>=<strong>true</strong></li></ol><p>You will see new <em>tools</em> options at your disposal. For my project “View PSI structure of current file” was the most helpful.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/590/0*t6xsyjALDR1Ew0zT" /></figure><p>Example of PSI file structure:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ClRG5Abk6BMTLo7n" /></figure><p>Back to the annotator example, lets take a look at the configuration:</p><pre><strong>&lt;extensions defaultExtensionNs=”com.intellij”&gt;</strong></pre><pre><strong>&lt;annotator language=”Scala” implementationClass=</strong>”com.google.idea.blaze.scala.sync.ImportIssueAnnotator”<strong>/&gt;</strong></pre><pre><strong>&lt;/extensions&gt;</strong></pre><p>Example of singling out java import statements:</p><pre><strong>package </strong>com.google.idea.blaze.java.sync;<br><br><strong>import </strong>com.google.idea.blaze.base.ui.problems.ImportIssue;<br><strong>import </strong>com.google.idea.blaze.base.ui.problems.ImportProblemContainerService;<br><strong>import </strong>com.intellij.lang.annotation.AnnotationHolder;<br><strong>import </strong>com.intellij.lang.annotation.Annotator;<br><strong>import </strong>com.intellij.openapi.components.ServiceManager;<br><strong>import </strong>com.intellij.psi.PsiElement;<br><strong>import </strong>com.intellij.psi.PsiImportStatement;<br><strong>import </strong>com.intellij.psi.PsiImportStaticStatement;<br><strong>import </strong>org.jetbrains.annotations.NotNull;<br><br><strong>import </strong>java.util.Optional;<br><br><strong>public class </strong>ImportIssueAnnotator <strong>implements </strong>Annotator {<br><br>    ImportProblemContainerService <strong>importProblemContainerService </strong>=<br>            ServiceManager.<em>getService</em>(ImportProblemContainerService.<strong>class</strong>);<br><br>    @Override<br>    <strong>public void </strong>annotate(@NotNull <strong>final </strong>PsiElement element, @NotNull AnnotationHolder holder) {<br>        <strong>if </strong>(element <strong>instanceof </strong>PsiImportStatement || element <strong>instanceof </strong>PsiImportStaticStatement) {<br>            Optional&lt;ImportIssue&gt; issue = <strong>importProblemContainerService</strong>.findIssue(element);<br>            <strong>if</strong>(issue.isPresent()){<br>                <strong>importProblemContainerService</strong>.createImportErrorAnnotation(element, holder, issue.get());<br>            }<br>        }<br>    }<br>}</pre><p>You can customize the highlighted section. I used tooltip and generic error (for red squiggly lines). Example of adding annotation on import line:</p><pre><strong>public void </strong>createImportErrorAnnotation(@NotNull PsiElement element, @NotNull AnnotationHolder holder, ImportIssue importIssue) {<br>    String tooltip = importIssue.getOriginalIssue().getMessage();<br>    Annotation errorAnnotation = holder.createErrorAnnotation(element, tooltip);<br>    errorAnnotation.setHighlightType(<strong><em>GENERIC_ERROR</em></strong>);<br>    String originalLine = importIssue.getOriginalLine();<br>    Project project = element.getProject();<br><br>    List&lt;Label&gt; importClassTargets = <br>           getImportClassTargets(element, originalLine, project).<br>                   stream().<br>                   distinct().<br>                   collect(Collectors.<em>toList</em>());<br>    Optional&lt;Label&gt; currentClassTarget = <br>           Optional.<em>of</em>(<br>              <em>findTarget</em>(<br>                  project, <br>                  element,      element.getContainingFile().getVirtualFile())<br>    );<br><br>    <strong>if</strong>(!importClassTargets.isEmpty() &amp;&amp; currentClassTarget.isPresent()){<br>        errorAnnotation.registerFix(<br>                <strong>new </strong>ImportIssueQuickFix(<br>                        tooltip.substring(7),<br>                        importIssue,<br>                        importClassTargets,<br>                        currentClassTarget.get()<br>                )<br>        );<br>    }<br>}</pre><p><strong>Part 3 — creating a quick fix action</strong></p><p>You may have noticed that when creating the annotation I registered an <a href="https://www.jetbrains.com/help/idea/intention-actions.html"><em>IntentionAction</em></a><em>. </em>This action will be called once user presses on the option in quick fix menu (invoke method will be called). Override the getText to customize the quick fix menu item text.</p><pre><strong>public class </strong>ImportIssueQuickFix <strong>implements </strong>IntentionAction {<br>    <strong>...</strong><br><br>    @Nls(capitalization = Nls.Capitalization.<strong><em>Sentence</em></strong>)<br>    @NotNull<br>    @Override<br>    <strong>public </strong>String getText() {<br>       <strong>return &quot;Add dependency to build file&quot;</strong>;       <br>    }<br><br>    ...<br><br>    @Override<br>    <strong>public void </strong>invoke(@NotNull Project project, Editor editor, PsiFile psiFile) <strong>throws </strong>IncorrectOperationException {<br>        //Place your quick fix code here<br>    }<br><br>    ...<br>}</pre><p><strong><em>Bonus section</em></strong></p><p>Some code samples for creating PSI elements I discovered along the way</p><p>Creating a comma element:</p><pre><strong>private </strong>PsiElement createCommaElement(Project project) {<br>    PsiManager psiManager = PsiManager.<em>getInstance</em>(project);<br>    <strong>final </strong>FileElement holderElement = DummyHolderFactory.<em>createHolder</em>(psiManager, <strong>null</strong>).getTreeElement();<br>    <strong>final </strong>LeafElement newElement = ASTFactory.<em>leaf</em>(<strong>new </strong>IElementType(<strong>&quot;COMMA&quot;</strong>, Language.<strong><em>ANY</em></strong>), holderElement.getCharTable().intern(<strong>&quot;,&quot;</strong>));<br>    holderElement.rawAddChildren(newElement);<br>    GeneratedMarkerVisitor.<em>markGenerated</em>(newElement.getPsi());<br>    <strong>return </strong>newElement.getPsi();<br>}</pre><p>String Literal element:</p><pre>PsiElementFactory factory = JavaPsiFacade.<em>getInstance</em>(project).getElementFactory();<br>PsiLiteralExpression stringLiteral = (PsiLiteralExpression)factory.createExpressionFromText(<strong>&quot;\&quot;&quot;</strong>+value+<strong>&quot;\&quot;&quot;</strong>, <strong>null</strong>);</pre><p>Enjoy!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f552f6309be2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wix-engineering/so-you-want-to-develop-an-intellij-plugin-f552f6309be2">So you want to develop an IntelliJ plugin</a> was originally published in <a href="https://medium.com/wix-engineering">Wix Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mixing Scala and Java — Invoking currying functions from Java]]></title>
            <link>https://medium.com/wix-engineering/mixing-scala-and-java-invoking-currying-functions-from-java-948963a52e81?source=rss-2bd369f44b13------2</link>
            <guid isPermaLink="false">https://medium.com/p/948963a52e81</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Idan Koch]]></dc:creator>
            <pubDate>Sat, 09 Dec 2017 21:46:49 GMT</pubDate>
            <atom:updated>2017-12-11T09:28:47.920Z</atom:updated>
            <content:encoded><![CDATA[<p>So…. you want to start trying out Scala. But you are stuck with legacy Java code. You can rewrite your code one class at a time or one flow at a time. But, if you don’t have the time to do so you can just invoke new Scala classes functions from old Java classes. Scala and Java are interoperable, however, the interoperability is not always straight forward. One example is when you want to invoke currying function from Java code.</p><p><strong>What is currying function?</strong></p><p>It’s not related to Indian food or an NBA superstar, if that’s what you think.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6cA81pbyTu5YEw532HMZmA.jpeg" /><figcaption>Currying — not the first thing that come to mind</figcaption></figure><p>I won’t get into details about currying or higher order functions but a definition and good examples can be found in <a href="https://dzone.com/articles/currying-functions-in-scala">Alexey Zvolinsky’s</a> article:</p><blockquote><a href="https://dzone.com/articles/currying-functions-in-scala">“A <strong>currying function</strong> is a function which could accept a fewer number of parameters than are declared, then it returns a function with unused parameters”</a></blockquote><p><strong>Example time:</strong></p><p>Let’s say I have old legacy service that does something:</p><pre><strong>public </strong>String doSomething(UUID userGuid) {<br>    log.info(“Yeah, you did it” + userGuid.toString());<br>    <strong>return “Great success”</strong>;<br>}</pre><p>Now, there is a cool service which you wrote that checks authorization for a certain user. The new authorization service is written in Scala and takes advantage of currying function to implement the following logic:</p><p><em>If the user is authorized invoke a function of your choosing — in our case doSomething. If not authorized throw an exception.</em></p><p>The authorization service might look something like this:</p><pre><strong>trait </strong>AuthorizationService {<br>      <strong>def </strong>authorizedFor[T](<br>           userGuid: UUID, <br>           permissionToBeChecked: String)<br>          (<em>doSomething</em>: AuthenticatedUserInfo =&gt; T): T</pre><pre>}</pre><p>The code that does the actual authorization might look something like so:</p><pre><strong>def </strong>authorizedFor(userGuid: UUID, <br>                  permissionToBeChecked: String]):<br>AuthroizedUserInfo = {</pre><pre>  <strong>if</strong>(“WRITE_PERMISSION” == permissionToBeChecked &amp;&amp; <br>     userGuid == <br>     UUID.fromString(<strong>&quot;00000000-0000-0000-0000-000000000000&quot; <br>    </strong>) {<br>     AuthrizedUserInfo(“howdy@doodie.com”)<br>  } <strong>else </strong>{<br>     <strong>throw </strong>UnauthorizedException(<br>       s“””$userGuid not authorised <strong>for </strong>$permissionToBeChecked “””)<br>  }</pre><pre>}</pre><p>Note, that your authorization service returns data about the authorized user <em>AuthroizedUserInfo</em>. If you wish, you can to use that information in your original method <em>doSomething</em>.</p><p><strong>So how can I invoke it from my old java code?</strong></p><p><a href="https://dzone.com/articles/introduction-functional-1">Java 8 reintroduced the concept of SAM interfaces as Functional interfaces</a>. Scala has extended the interface as a bunch of abstract classes: <em>AbstractFunction0</em>, <em>AbstractFunction1, AbstractFunction2.. AbstractFunction22</em>. Basically, each class represents a function with a set of input parameters:</p><p><em>AbstractFunction0 </em>— zero input parameters</p><p><em>AbstractFunction1 </em>— one input parameter</p><p>...</p><p><em>AbstractFunction 22 </em>— 22 input parameters</p><h3>Putting it all together</h3><pre>public String doSomething(UUID userGuid) {<br>    Object result = authorizationService.authorizedFor(<br>    userGuid,<br>    “WRITE_PERMISSION”,<br>    <strong>new </strong>AbstractFunction1 &lt;AuthenticatedUserInfo, Object &gt; () {<br>     <br>     @Override<br>      public Object apply(AuthenticatedUserInfo authenticatedUser) {<br>        <em>log</em>.info(“Yeah, you did it ” +authenticatedUser.email()<br>      );<br>        <strong>return<br>      </strong>“Great success”;<br>      }<br>    }<br>   );<br>   <strong>return </strong>(String) result;<br>}</pre><p>Enjoy!!!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=948963a52e81" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wix-engineering/mixing-scala-and-java-invoking-currying-functions-from-java-948963a52e81">Mixing Scala and Java — Invoking currying functions from Java</a> was originally published in <a href="https://medium.com/wix-engineering">Wix Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>