<?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[Lonto - Medium]]></title>
        <description><![CDATA[We specialize in HR Tech, EdTech, Marketing Technology, DevOps and custom web and mobile services. - Medium]]></description>
        <link>https://medium.com/lonto-digital-services-integrator?source=rss----d9314f378ff---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Lonto - Medium</title>
            <link>https://medium.com/lonto-digital-services-integrator?source=rss----d9314f378ff---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 12:52:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/lonto-digital-services-integrator" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Creating a Text Editor in React.js]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/creating-a-text-editor-in-react-js-db006a120d85?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/db006a120d85</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[draftjs]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Danila Reutov]]></dc:creator>
            <pubDate>Wed, 25 Oct 2023 07:40:32 GMT</pubDate>
            <atom:updated>2025-04-02T07:17:17.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*Ru-mOd4RcKElwYdob_Pt7Q.png" /></figure><p>Hi! My name is Danila, and I am a front-end teamlead at <a href="https://www.lonto.io/">Lonto</a>.</p><p>Once I needed to implement a custom text editor in a project on React.js. I found this task quite interesting and decided to describe my experience. In this guide I will describe a step by step guide on creating a text editor with basic features.</p><p>I hope you’ll find it useful.</p><p>Contents:</p><ol><li>The description of the task</li><li>What is Draft.js?</li><li>Architecture</li><li>Let’s start coding</li><li>Creating simple blocks</li><li>Inline text styles</li><li>Creating interactive elements</li><li>Handling keyboard shortcuts</li><li>HTML export-import in the editor</li><li>Instead of conclusion</li></ol><h3>1. Task description</h3><p>Let’s make up some requirements for our editor. It should:</p><ol><li>Have preset element styles: headings, lists, etc.</li><li>Be able to format text: bold, italic, etc.</li><li>Support interactive elements, such as links</li><li>Support keyboard shortcuts</li><li>Be able to import/export content to HTML</li></ol><p>Browsers can handle native text events differently, so it was difficult to implement everything from scratch.</p><p>Thus, I started looking for ready-made solutions. And the most popular was Draft.js.</p><h3>2. What is Draft.js?</h3><p><a href="https://draftjs.org/">Draft.js</a> is a framework for working with text on React.js. It allows you to create an editor state that stores all information about content, cursor position, and more. It also provides cross-browser features that can conveniently change this state. Draft.js handles immutable data with <a href="https://immutable-js.com/">immutable.js</a>. This means that when the state changes, we overwrite it completely with the new version.</p><p>Content in the Draft.js editor is built from <a href="https://draftjs.org/docs/api-reference-content-block/">blocks</a>. A block is a data structure that stores information about the text within it. Each block can be given its own unique data and render settings: set the tag, styles, attributes, or just specify the React component. You can apply <a href="https://draftjs.org/docs/advanced-topics-inline-styles">inline styles</a> (e.g., bold) to any text fragment in the block. And to create more complex and interactive elements, Draft.js has <a href="https://draftjs.org/docs/advanced-topics-entities/">Entities</a> and <a href="https://draftjs.org/docs/advanced-topics-decorators/">Decorators</a>. You can use them to render custom React components and link them to text fragments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*0igDBFSY_I9zPY_C" /></figure><h3>3. Architecture</h3><p>Our component will consist of several parts:</p><ol><li>Editor window</li><li>Controls</li></ol><p>We will put the entire API of our editor in useEditor — a separate React hook.</p><p>The design of the editor can be customizable, and the controls can be located separately from the editor window. To avoid props drilling when passing the editor API to components, we will use the React context. This will allow us to easily get the necessary data and functions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/0*uEezyfFgO3s2OYZT" /></figure><p>Our editor’s architecture</p><h3>4. Let’s start coding</h3><p>To make things simpler, in this guide we will use the typescript template of <a href="https://create-react-app.dev/">CRA</a>.</p><pre>$ npx create-react-app editor --template typescript</pre><p>Let’s establish the necessary dependencies:</p><pre>$ yarn add draft-js draft-convert</pre><ul><li><em>draft-js</em> is a Draft.js framework</li><li><em>draft-convert</em> is a library to easily import and export data from Draft.js. We’ll have a closer look at it in the Export-import of HTML to the editor part.</li></ul><p>Let’s set the types for the libraries described above:</p><pre>$ yarn add -D @types/draft-js @types/draft-convert </pre><p>And create the <em>useEditor.tsx</em> file. It will contain the React hook, in which we will store all the logic of our editor:</p><pre>// src/TextEditor/useEditor.tsx<br>import { EditorState } from &#39;draft-js&#39;;<br>import * as React from &#39;react&#39;;<br> <br>export type EditorApi = {<br>  state: EditorState;<br>  onChange: (state: EditorState) =&gt; void;<br>}<br><br>export const useEditor = (): EditorApi =&gt; {<br>  const [state, setState] = React.useState(() =&gt; EditorState.createEmpty());<br>  <br>  return React.useMemo(() =&gt; ({<br>    state,<br>    onChange: setState<br>  }), [state])<br>}</pre><p>Now, we create an empty immutable state of our editor with the <em>EditorState.createEmpty()</em> method and store it in the local state. We will gradually add features and logic to it.</p><p>Let’s create a React Context to throw the editor’s API:</p><pre>// src/TextEditor/context.tsx<br>import * as React from &#39;react&#39;;<br>import { EditorApi, useEditor } from &#39;./useEditor&#39;;<br><br>const TextEditorContext = React.createContext&lt;EditorApi | undefined&gt;(undefined);<br><br>export const useEditorApi = () =&gt; {<br>  const context = React.useContext(TextEditorContext);<br>  if (context === undefined) {<br>    throw new Error(&#39;useEditorApi must be used within TextEditorProvider&#39;);<br>  }<br>  <br>  return context;<br>}<br><br>export const TextEditorProvider: React.FC = ({ children }) =&gt; {<br>  const editorApi = useEditor();<br>  <br>  return (<br>    &lt;TextEditorContext.Provider value={editorApi}&gt;<br>      {children}<br>    &lt;/TextEditorContext.Provider&gt;<br>  )<br>}</pre><p>Now we can access the editor functions anywhere in our app using the <em>useEditorApi</em> hook:</p><pre>const editorApi = useEditorApi();</pre><p>Let’s wrap the components with a TextEditorProvider:</p><pre>// src/App.tsx<br>function App() {<br>  return (<br>    &lt;TextEditorProvider &gt;<br>      &lt;ToolPanel /&gt;<br>      &lt;TextEditor /&gt;<br>    &lt;/TextEditorProvider&gt;<br>  );<br>}</pre><p>We’ll create the <em>TextEditor</em> window component:</p><pre>// src/TextEditor/index.ts<br>export { default } from &#39;./TextEditor&#39;;</pre><pre>// src/TextEditor/TextEditor.tsx<br>import * as React from &#39;react&#39;;<br>import { Editor } from &#39;draft-js&#39;;<br>import { useEditorApi } from &#39;./context&#39;;<br>import cn from &#39;classnames&#39;;<br>import &#39;./TextEditor.scss&#39;;<br><br>export type TextEditorProps = {<br>  className?: string;<br>}<br><br>const TextEditor: React.FC&lt;TextEditorProps&gt; = ({ className }) =&gt; {<br>  const { state, onChange } = useEditorApi();<br>  <br>  return (<br>    &lt;div className={cn(&quot;text-editor&quot;, className)}&gt;<br>      &lt;Editor<br>        placeholder=&quot;Введите ваш текст&quot;<br>        editorState={state}<br>        onChange={onChange}<br>      /&gt;<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default TextEditor;</pre><p>We’ve plugged in the basic <em>Editor</em> component from the <em>Draft.js</em> package. It will create the editable field and manage the content. We’ll bind it to the previously created editor’s API.</p><p>Let’s create a toolbar component:</p><pre>// src/ToolPanel/index.ts<br>export { default } from &#39;./ToolPanel&#39;;</pre><pre>// src/ToolPanel/ToolPanel.tsx<br>import * as React from &#39;react&#39;;<br>import { EditorApi } from &#39;../useEditor&#39;;<br>import &#39;./ToolPanel.scss&#39;;<br><br>const ToolPanel:React.FC&lt;ToolPanelProps&gt; = ({ className } ) =&gt; {<br>  return (<br>    &lt;div className={cn(&#39;tool-panel&#39;, className)}&gt;<br>      {/* Здесь будет код для элементов управления */}<br>    &lt;/div&gt;<br>  );<br>}<br><br>export default ToolPanel;</pre><h3>5. Creating simple blocks</h3><p>We’ve created an editor, but so far it’s no different than a simple <em>textarea</em>. Let’s add the ability to create blocks.</p><p>Draft.js contains settings for basic block types by default. A complete list can be found <a href="https://draftjs.org/docs/advanced-topics-custom-block-render-map">here</a>.</p><p>Let’s create <em>config.ts </em>— a configuration file:</p><pre>// src/TextEditor/config.ts<br>export enum BlockType {<br>  /* Заголовки */<br>  h1 = &#39;header-one&#39;,<br>  h2 = &#39;header-two&#39;,<br>  h3 = &#39;header-three&#39;,<br>  h4 = &#39;header-four&#39;,<br>  h5 = &#39;header-five&#39;,<br>  h6 = &#39;header-six&#39;,<br>  /* Цитата */<br>  blockquote = &#39;blockquote&#39;,<br>  /* Блок с кодом */<br>  code = &#39;code-block&#39;,<br>  /* Список */<br>  list = &#39;unordered-list-item&#39;,<br>  /* Нумерованный список */<br>  orderList = &#39;ordered-list-item&#39;,<br>  /* Сноска */<br>  cite = &#39;cite&#39;,<br>  /* Простой текст */<br>  default = &#39;unstyled&#39;,<br>}</pre><p>We have described the enum with block type names, and added a new footnote <em>cite</em> block. But so far the editor knows nothing about how to handle new block types. To add custom blocks to Draft.js, you need to create an <a href="https://draftjs.org/docs/advanced-topics-custom-block-render-map#configuring-block-render-map">immutable block map</a>. Let’s use the <em>Immutable.Map</em> method from the <em>immutable</em> package (it is installed with Draft.js). We’ve set the name of our new block (<em>cite</em>) and specified the name of the tag with which it should appear in the DOM. To avoid describing the default blocks, let’s merge the default block map with our map using the <em>DefaultDraftBlockRenderMap.merge</em> method:</p><pre>// src/TextEditor/config.ts<br>import Immutable from &#39;immutable&#39;;<br>import { DefaultDraftBlockRenderMap } from &#39;draft-js&#39;;<br><br>...<br><br>const CUSTOM_BLOCK_RENDER_MAP = Immutable.Map({<br>  [BlockType.cite]: {<br>    element: &#39;cite&#39;, &lt;-- название тега<br>  },<br>});<br><br>export const BLOCK_RENDER_MAP = DefaultDraftBlockRenderMap.merge(CUSTOM_BLOCK_RENDER_MAP);</pre><p>Next, let’s set the editor’s new configuration:</p><pre>// src/TextEditor/TextEditor.tsx<br>import { BLOCK_RENDER_MAP } from &#39;./config&#39;;<br>...<br>&lt;Editor<br>    ...<br>    blockRenderMap={BLOCK_RENDER_MAP}<br>/&gt;</pre><p>Our editor can handle block types now. To create block type controls, we need to add two fields to the <em>useEditor</em> hook:</p><ul><li>toggleBlockType — a function for toggling the block type</li><li>currentBlockType — a variable with the value of the current block type that lets us add an active state to the element</li></ul><p>Draft.js contains the RichUtils class with auxiliary methods for text editing. To implement <em>toggleBlockType</em>, let’s use the <em>RichUtils.toggleBlockType</em> method to apply a specific block type to the current state of the editor:</p><pre>// src/TextEditor/useEditor.tsx<br>export type EditorApi = {<br>  ...<br>  toggleBlockType: (blockType: BlockType) =&gt; void;<br>}<br><br>export const useEditor = (html?: string): EditorApi =&gt; {<br>    ...<br>    const toggleBlockType = React.useCallback((blockType: BlockType) =&gt; {<br>      setState((currentState) =&gt; RichUtils.toggleBlockType(currentState, blockType))<br>    }, []);<br>    ...<br>}</pre><p>The <em>currentBlockType</em> implementation will look like this:</p><pre>// src/TextEditor/useEditor.tsx<br>import { BlockType } from &#39;./config&#39;;<br><br>export type EditorApi = {<br>  ...<br>  currentBlockType: BlockType;<br>}<br><br>export const useEditor = (html?: string): EditorApi =&gt; {<br>    ...<br>    const currentBlockType = React.useMemo(() =&gt; {<br>      /* Шаг 1 */<br>      const selection = state.getSelection();<br>      /* Шаг 2 */<br>      const content = state.getCurrentContent();<br>      /* Шаг 3 */<br>      const block = content.getBlockForKey(selection.getStartKey());<br>      /* Шаг 4 */<br>      return block.getType() as BlockType;<br>    }, [state]);<br>    ...<br>}</pre><p>Let’s take a closer look at the code.</p><p><strong>Step 1:</strong> We get the map that stores <a href="https://draftjs.org/docs/api-reference-selection-state/#internaldocs-banner">info</a> about where the user’s carriage is located.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/197/0*0B4hPY6oqty7JJeJ" /></figure><p>Let me remind you that Draft.js works with immutable data, so you can use the <em>toJS</em> method to see what is stored in the <em>selection</em></p><p><strong>Step 2:</strong> We get our editor’s <a href="https://draftjs.org/docs/api-reference-content-state/#internaldocs-banner">content map</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/0*7TgxfBBR6lwaqwiz" /></figure><p><strong>Step 3:</strong> We use the key field to find the current block. The key is a unique hash that Draft.js has generated.</p><p><strong>Step 4:</strong> We get the type of the found block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*Lnv262ooMFIsaVZ1DE6xjg.gif" /></figure><h3>6. Inline text styles</h3><p>Now let’s create functions to apply styles to the highlighted text.</p><p>Draft.js has built-in style types for inline styles. Let’s use them and add our own custom type. Our style will change the background and font color.</p><p>First, let’s describe the enum for inline styles in our config:</p><pre>// src/TextEditor/config.ts<br>export enum InlineStyle {<br>  BOLD = &#39;BOLD&#39;,<br>  ITALIC = &#39;ITALIC&#39;,<br>  UNDERLINE = &#39;UNDERLINE&#39;,<br>  ACCENT = &#39;ACCENT&#39; // our custom style code<br>}</pre><p>Since we have a custom style, we need to describe what styles it will apply. To do this, let’s create a map:</p><pre>// src/TextEditor/config.ts<br>export const CUSTOM_STYLE_MAP = {<br>  [InlineStyle.ACCENT]: {<br>    backgroundColor: &#39;#F7F6F3&#39;,<br>    color: &#39;#A41E68&#39;,<br>  },<br>};</pre><p>And now we need to set the map in the <em>Editor</em>:</p><pre>// src/TextEditor/TextEditor.tsx<br>&lt;Editor<br>  customStyleMap={CUSTOM_STYLE_MAP}<br>  ...<br>/&gt;</pre><p>Now the editor knows how to handle our styles. Next, we need to implement inline styles control buttons:</p><ul><li><em>toggleInlineStyle</em> is the function for toggling the inline style on or off;</li><li><em>hasInlineStyle</em> is a function that indicates whether a particular style is applied to the highlighted text.</li></ul><p>Again, we can use <em>RichUtils</em> to accomplish this task:</p><pre>// src/TextEditor/useEditor.ts<br>const toggleInlineStyle = React.useCallback((inlineStyle: InlineStyle) =&gt; {<br>  setState((currentState) =&gt; RichUtils.toggleInlineStyle(currentState, inlineStyle))<br>}, []);<br><br>const hasInlineStyle = React.useCallback((inlineStyle: InlineStyle) =&gt; {<br>  /* We get an immutable Set with style keys */<br>  const currentStyle = state.getCurrentInlineStyle();<br>  /* We check to see if the style we&#39;ve passed is there */<br>  return currentStyle.has(inlineStyle);<br>}, [state]);</pre><p>Now we can easily add inline style control buttons:</p><pre>// src/ToolPanel/ToolPanel.tsx<br>const INLINE_STYLES_CODES = Object.values(InlineStyle);<br><br>const ToolPanel: React.FC = () =&gt; {<br>  const { toggleInlineStyle, hasInlineStyle } = useEditorApi();<br>  <br>  return (<br>    &lt;div className=&quot;tool-panel&quot;&gt;<br>      ...<br>      {INLINE_STYLES_CODES.map((code) =&gt; {<br>        const onMouseDown = (e) =&gt; {<br>          e.preventDefault();<br>          toggleInlineStyle(code);<br>        };<br>    <br>        return (<br>          &lt;button<br>            key={code}<br>            className={cn(<br>              &quot;tool-panel__item&quot;,<br>              hasInlineStyle(code) &amp;&amp; &quot;tool-panel__item_active&quot;<br>            )}<br>            onMouseDown={onMouseDown}<br>          &gt;<br>            {code}<br>          &lt;/button&gt;<br>        );<br>      })}<br>    &lt;/div&gt;<br>  );<br>};</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*bQQClr4VbM3_I8qn_QHZrA.gif" /></figure><h3>7. Creating interactive elements</h3><p>Let’s look at the process of creating interactive elements using the example of inserting links. We will use <a href="https://draftjs.org/docs/api-reference-entity/#internaldocs-banner">Entities</a> for that purpose. Entity is an object that stores metadata for a specific text fragment. It has three properties:</p><ul><li>type — Entity type name</li><li>mutability — type of text binding (more on it below)</li><li>data — metadata</li></ul><p>Let’s create an <em>Entity</em> type enumeration in the config:</p><pre>// src/TextEditor/config.ts<br>export enum EntityType {<br>  link = &#39;link&#39;,<br>}</pre><p>Next, let’s create a <em>Link</em> React component which will be displayed in place of the links:</p><pre>// src/TextEditor/Link/Link.tsx<br>import { ContentState } from &#39;draft-js&#39;;<br>import * as React from &#39;react&#39;;<br><br>type LinkProps = {<br>  children: React.ReactNode;<br>  contentState: ContentState;<br>  entityKey: string;<br>}<br><br>const Link: React.FC&lt;LinkProps&gt; = ({ contentState, entityKey, children }) =&gt; {<br>  /* We get the URL using the unique Entity key */<br>  const { url } = contentState.getEntity(entityKey).getData();<br>  <br>  return (<br>    &lt;a href={url}&gt;<br>      {children}<br>    &lt;/a&gt;<br>  );<br>}<br><br>export default Link;</pre><p>Each <em>Entity</em> is assigned a unique hash key when it is created. We can use it to access the stored metadata — the <em>url</em> in this case. We will set it up when we create the Entity link.</p><p>There is a system of <a href="https://draftjs.org/docs/advanced-topics-decorators/">Decorators</a> that lets Draft.js understand which text fragment the Entity is attached to.</p><p>The decorator consists of three parts:</p><ul><li><em>strategy</em> is the function that searches the text fragment in the place of which you want to display a component</li><li><em>component</em> is a component you want to display</li><li>props are props to be passed to the component</li></ul><p>Let’s create a decorator to bind links:</p><pre>// src/TextEditor/Link/index.ts<br>import Link from &quot;./Link&quot;;<br>import { EntityType } from &quot;../config&quot;;<br>import { ContentBlock, ContentState, DraftDecorator } from &quot;draft-js&quot;;<br><br>function findLinkEntities(<br>  /* The block in which the last change was made */<br>  contentBlock: ContentBlock,<br>  /* A function to be called with text fragment indexes */<br>  callback: (start: number, end: number) =&gt; void,<br>  /* Current content map */<br>  contentState: ContentState<br>): void {<br>  /* We perform the filter function for each character in the block */<br>  contentBlock.findEntityRanges((character) =&gt; {<br>    /* We get the Entity key */<br>    const entityKey = character.getEntity();<br>    /* We check that Entity belongs to the Entity link type */<br>    return (<br>      entityKey !== null &amp;&amp;<br>      contentState.getEntity(entityKey).getType() === EntityType.link<br>    );<br>  }, callback);<br>}<br><br>const decorator: DraftDecorator = {<br>  strategy: findLinkEntities,<br>  component: Link,<br>};<br><br>export default decorator;</pre><p>Now we can connect the created decorator to our editor:</p><pre>// src/TextEditor/useEditor.tsx<br>import { CompositeDecorator } from &#39;draft-js&#39;;<br>import LinkDecorator from &#39;./Link&#39;;<br><br>/* We combine the decorators into one */<br>const decorator = new CompositeDecorator([LinkDecorator]);<br><br>export const useEditor = (): EditorApi =&gt; {<br>    const [state, setState] = React.useState(() =&gt; EditorState.createEmpty(decorator));<br>    ...</pre><p>Great! Now our editor can handle links. Let’s tell it how to add and edit them.</p><p>Since there can be several Entity types in the editor, let’s create a common function to add an <em>Entity</em>. It will only be available inside the hook and won’t be available in components. To add a link type, let’s create a separate addLink function. It will be available in the editor’s API:</p><pre>// src/TextEditor/useEditor.tsx<br>import { EditorState, RichUtils } from &#39;draft-js&#39;;<br><br>export const useEditor = (): EditorApi =&gt; {<br>    ...<br>    const addEntity = React.useCallback((entityType: EntityType, data: Record&lt;string, string&gt;, mutability: DraftEntityMutability) =&gt; {<br>     setState((currentState) =&gt; {<br>        /* We retrieve the current content */<br>       const contentState = currentState.getCurrentContent();<br>        /* We create an Entity with data */<br>       const contentStateWithEntity = contentState.createEntity(entityType, mutability, data);<br>        /* We get a unique Entity key */<br>       const entityKey = contentStateWithEntity.getLastCreatedEntityKey();<br>        /* We combine the current state with the new one */<br>       const newState = EditorState.set(currentState, { currentContent: contentStateWithEntity });<br>       /* We insert the link to the specified place */<br>        return RichUtils.toggleLink(newState, newState.getSelection(), entityKey);<br>    })<br>  }, []);<br><br>  const addLink = React.useCallback((url) =&gt; {<br>  addEntity(EntityType.link, { url }, &#39;MUTABLE&#39;)<br>  }, [addEntity]);<br> <br> return {<br>    ...<br>    addLink<br> }<br>}</pre><p><em>Entity</em> has three text binding modes:</p><ol><li><em>MUTABLE</em>: the text can be changed</li><li><em>IMMUTABLE</em>: if you change the text, the <em>Entity</em> will be deleted</li><li><em>SEGMENTED</em>: it works in the same way as <em>IMMUTABLE</em> with the only difference that if you delete a character from the text consisting of several words, the word will be removed, but the remaining words will remain bound to the <em>Entity</em>. (Example: “Katy wa|shed the dishes” → [backspace] → “Katy the dishes”)</li></ol><p>We’ve chosen the <em>MUTABLE</em> mode because the link text can be editable.</p><p>We can implement the ‘Add a link’ button easily now. To specify the address of the link, let’s use the <em>prompt</em>:</p><pre>// src/ToolPanel/ToolPanel.tsx<br>const ToolPanel: React.FC = () =&gt; {<br>  const { addLink } = useEditorApi();<br><br>  const handlerAddLink = () =&gt; {<br>   const url = prompt(&#39;URL:&#39;);<br><br>    if (url) {<br>      addLink(url);<br>    }<br>  }<br><br> return (<br>    ...<br>    &lt;button onClick={handlerAddLink}&gt;<br>     Add a link<br>    &lt;/button&gt;<br>    ...<br> );<br>}</pre><p>Links are added. Let’s refine the editor so you can edit the <em>URL</em> of an already created link.</p><p>To simplify the example, let’s make it so that when you click on the link in the editor, the <em>prompt</em> with the pre-filled <em>url</em> appears again.</p><p>Let’s process the click in the component:</p><pre>// src/TextEditor/Link/Link.tsx<br>import { useEditorApi } from &#39;../context&#39;;<br><br>const Link: React.FC&lt;LinkProps&gt; = ({ contentState, entityKey, children }) =&gt; {<br>  const { setEntityData } = useEditorApi();<br>  const { url} = contentState.getEntity(entityKey).getData();<br>  <br>  const handlerClick = () =&gt; {<br>    const newUrl = prompt(&#39;URL:&#39;, url);<br>    if (newUrl) {<br>      setEntityData(entityKey, { url: newUrl });<br>    }<br>  }<br>  <br>  return (<br>    &lt;a href={url} onClick={handlerClick}&gt;<br>      {children}<br>    &lt;/a&gt;<br>  );<br>}</pre><p>And let’s create a function to overwrite the <em>Entity</em> data:</p><pre>// src/TextEditor/useEditor.tsx<br>export const useEditor = (): EditorApi =&gt; {<br>    ...<br>    const setEntityData = React.useCallback((entityKey, data) =&gt; {<br>    setState((currentState) =&gt; {<br>      /* We retrieve the current content */<br>      const content = currentState.getCurrentContent();<br>      /* Let&#39;s combine the current Entity data with the new data */<br>      const contentStateUpdated = content.mergeEntityData(<br>        entityKey,<br>        data,<br>      )<br>      /* We update the state of the editor, indicating the type of change */<br>      return EditorState.push(currentState, contentStateUpdated, &#39;apply-entity&#39;);<br>    })<br>  }, []);<br><br>  export {<br>    ...<br>    setEntityData<br> }<br>}</pre><p>There are <a href="https://draftjs.org/docs/api-reference-editor-change-type/">several types</a> of editor state changes. And we need each of them so that Draft.js could correctly determine how a change affects certain functions. For example, redo and undo.</p><p>That’s it. Now we can easily add and edit custom <em>Entities</em> in our editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*e4nyBZqQxwzV-79YK4g_NQ.gif" /></figure><h3>8. Handling keyboard shortcuts</h3><p>Many text editors let you edit content using keyboard shortcuts. Draft.js has a mechanism for implementing such a behavior. The shortcut must perform a specific action — a command. Let’s create a function to handle these commands.</p><pre>// src/TextEditor/useEditor.tsx<br>export const useEditor = (): EditorApi =&gt; {<br> ...<br>  const handleKeyCommand = React.useCallback((command: DraftEditorCommand, editorState: EditorState) =&gt; {<br>   const newState = RichUtils.handleKeyCommand(editorState, command);<br><br>    if (newState) {<br>    setState(newState);<br>    return &#39;handled&#39;;<br>  }<br><br>  return &#39;not-handled&#39;;<br>  }, []);<br><br>  export {<br>    ...<br>    handleKeyCommand <br> }<br>}</pre><p>The function takes the name of the command and the current state of the editor as input, and it should return one of the two values:</p><ul><li><em>handled</em> — command applied</li><li><em>not-handled</em> — command not applied</li></ul><p>You should always try to work with the latest version to avoid the race of state updates. You can read more about that <a href="https://draftjs.org/docs/advanced-topics-editorstate-race-conditions/">here</a>.</p><p>Let’s add the handling of standard keyboard shortcuts with <em>RichUtils.handleKeyCommand</em>. For example, <em>ctrl + I</em> or <em>cmd + I</em> to apply a previously created <em>ITALIC</em> style.</p><p>Next, we need to throw our function into the Editor component:</p><pre>// src/TextEditor/TextEditor.tsx<br>&lt;Editor<br>  handleKeyCommand={editorApi.handleKeyCommand}<br>  ...<br>/&gt;</pre><p>Great, now we can handle standard keyboard shortcuts. But we’ll go further and add our own combination for our <em>ACCENT</em> custom text style. First, let’s extend the type of standard commands so that the ts doesn’t swear at us:</p><pre>// src/TextEditor/config.ts<br>import { DraftEditorCommand} from &#39;draft-js&#39;;<br><br>export type KeyCommand = DraftEditorCommand | &#39;accent&#39;; // a custom command</pre><p>Next, let’s create a function to handle key presses:</p><pre>// src/TextEditor/useEditor.tsx<br>import { KeyBindingUtil, getDefaultKeyBinding } from &#39;draft-js&#39;;<br><br>export const useEditor = (): EditorApi =&gt; {<br> ...<br>  const handlerKeyBinding = React.useCallback((e: React.KeyboardEvent) =&gt; {<br>   /* We check if the q + ctrl/cmd key is pressed */<br>    if (e.keyCode === 81 &amp;&amp; KeyBindingUtil.hasCommandModifier(e)) {<br>     return &#39;accent&#39;;<br>    }<br>   <br>    return getDefaultKeyBinding(e);<br>}, []);<br><br>return {<br>    ...<br>    handlerKeyBinding <br> }<br>}</pre><p>Note that we use the <em>getDefaultKeyBinding</em> function. It contains the logic for the standard keyboard shortcuts. We also use the <em>KeyBindingUtil.hasCommandModifier</em> utility to detect when the user presses a command key: ctrl or cmd. So, when you press <em>q + ctrl</em> or <em>q + cmd</em> the <em>accent</em> command will be executed. Now you need to handle it in <em>handleKeyCommand</em>:</p><pre>// src/TextEditor/useEditor.tsx<br>const handleKeyCommand = React.useCallback((command: DraftEditorCommand, editorState: EditorState) =&gt; {<br>   if (command === &#39;accent&#39;) {<br>    toggleInlineStyle(InlineStyle.ACCENT);<br>    return &#39;handled&#39;;<br>  }<br>  ...<br>}, []);</pre><p>This way we can add custom keyboard shortcuts.</p><h3>9. HTML export-import in the editor</h3><p>The ability to export and import data is an essential part of a text editor. Draft.js has a <a href="https://draftjs.org/docs/api-reference-data-conversion/#converttoraw">convertToRaw</a> function that allows you to load a JSON with data about all the content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*nPlQnsAIR7XRxSbR" /></figure><p>From this data, you can generate HTML. Having browsed the web and the npm, I found several packages that allowed me to specify in detail how to convert content to and from HTML. After weighing the pros and cons, I settled on the <a href="https://github.com/HubSpot/draft-convert"><em>draft-convert</em></a> package<em> (which we installed during the project set-up)</em> because it allowed me to conveniently implement the desired features.</p><p>Let’s create a <em>convert.tsx</em> file. In it, we will declare the functions for converting the editor’s state to HTML and back.</p><p>Let’s create a function to convert the editor’s state to HTML. In it, we will describe the rules by which we want to convert the editor’s data into layout:</p><pre>// src/TextEditor/convert.tsx<br>import { CUSTOM_STYLE_MAP, BlockType, EntityType, InlineStyle } from &#39;./config&#39;;<br><br>export const stateToHTML = convertToHTML&lt;InlineStyle, BlockType&gt;({<br>  styleToHTML: (style) =&gt; {<br>    switch (style) {<br>      case InlineStyle.BOLD:<br>        return &lt;strong /&gt;;<br>      ...<br>      case InlineStyle.ACCENT:<br>        return &lt;span className=&quot;accent&quot; style={CUSTOM_STYLE_MAP[InlineStyle.ACCENT]} /&gt;;<br>      default:<br>        return null;<br>    }<br>  },<br>  blockToHTML: (block) =&gt; {<br>    switch (block.type) {<br>      case BlockType.h1:<br>          return &lt;h1 /&gt;;<br>        ...<br>      case BlockType.default:<br>        return &lt;p /&gt;;<br>      default:<br>        return null;<br>    }<br>  },<br>  entityToHTML: (entity, originalText) =&gt; {<br>    if (entity.type === EntityType.link) {<br>      return (<br>        &lt;a href={entity.data.url}&gt;<br>          {originalText}<br>        &lt;/a&gt;<br>      );<br>    }<br>    return originalText;<br>  },<br>});</pre><p>To use our converter, let’s create a <em>toHtml</em> function:</p><pre>// src/TextEditor/useEditor.tsx<br>export const useEditor = (): EditorApi =&gt; {<br> ...<br>  const toHtml = React.useCallback(() =&gt; {<br>   return stateToHTML(state.getCurrentContent());<br>  }, [state]);<br><br>  return {<br>    ...<br>    toHtml <br> }<br>}</pre><p>And for example, let’s add a button that will output the generated HTML to the console:</p><pre>&lt;button onClick={toHtml}&gt;Print&lt;/button&gt;</pre><p>Great, now we can export the HTML from our editor. Now let’s add the ability to import the original content. Let’s describe the rules for converting HTML into the editor data:</p><pre>// src/TextEditor/convert.tsx<br>export const HTMLtoState = convertFromHTML&lt;DOMStringMap, BlockType&gt;({<br>  htmlToStyle: (nodeName, node, currentStyle) =&gt; {<br>    if (nodeName === &#39;strong&#39;) {<br>        return currentStyle.add(InlineStyle.BOLD);<br>    }<br>    ...<br>    if (nodeName === &#39;span&#39; &amp;&amp; node.classList.contains(&#39;accent&#39;)) {<br>      return currentStyle.add(InlineStyle.ACCENT);<br>    }<br><br>    return currentStyle;<br>  },<br>  htmlToBlock(nodeName, node) {<br>    switch (nodeName) {<br>      case &#39;h1&#39;:<br>        return BlockType.h1;<br>      ...<br>      case &#39;div&#39;:<br>      case &#39;p&#39;:<br>        return BlockType.default;<br>      default:<br>        return null;<br>    }<br>  },<br>  htmlToEntity: (nodeName, node, createEntity) =&gt; {<br>    if (nodeName === &#39;a&#39; &amp;&amp; node.href) {<br>      return createEntity(EntityType.link, &#39;MUTABLE&#39;, { url: node.href });<br>    }<br><br>    return undefined;<br><br>  },<br>});</pre><p>Now let’s connect the HTML converter to the editor. To do this, let’s use the standard <em>EditorState.createWithContent</em> method and refine the <em>EditorApi</em>:</p><pre>// src/TextEditor/useEditor.tsx<br>...<br>export const useEditor = (html?: string): EditorApi =&gt; {<br>  const [state, setState] = React.useState(() =&gt;<br>    html<br>      ? EditorState.createWithContent(HTMLtoState(html), decorator)<br>      : EditorState.createEmpty(decorator)<br>  );<br>  ...<br>}</pre><p>Now all we have to do is to pass the HTML! Our editor knows how to load with preset content.</p><h3>10. Instead of conclusion</h3><p>Progress does not stand still: more and more sophisticated APIs and libraries appear every day. In this article I tried to show how I solved this task a while ago. However, in my case, Mobx was connected to the project, and all the features of the useEditor hook were implemented as a class. But since the task is quite extensive, I decided not to overload the article with data and use the standard and well-known React.js hooks.</p><p>You can find the full code from the article <a href="https://github.com/ktsstudio/editor-react">here</a>.</p><p>If you have solved similar problems too, you are welcome to share your experience in the comments. What tools did you use?</p><p>Thank you for your attention!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db006a120d85" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/creating-a-text-editor-in-react-js-db006a120d85">Creating a Text Editor in React.js</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Create a type-safe Dependency Injection Container for an iOS application. Part 1]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/create-a-type-safe-dependency-injection-container-for-an-ios-application-part-1-c076daf107bc?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/c076daf107bc</guid>
            <category><![CDATA[mobile-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-development]]></category>
            <dc:creator><![CDATA[Aleksandr Sychev]]></dc:creator>
            <pubDate>Thu, 29 Jun 2023 10:38:45 GMT</pubDate>
            <atom:updated>2023-06-29T10:38:45.577Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMnvLjxtidlYwvHRhm4pdQ.jpeg" /></figure><p>Hello, reader! My name is Aleksandr, and I am an iOS tech lead at <a href="https://www.lonto.io/">Lonto</a>.</p><p>In the series of articles, I will share my ideas of Dependency Injection and try to solve the main issue of the library solutions for DI: <em>we need to know exactly that the screen will be assembled, dependencies will catch up, and all errors will be identified at the compilation stage.</em></p><p>To dig into and cover most of the possible pitfalls, we need a large project with many screens, ideally, broken down into modules. What I offer is to go this way together and write the project together with me.</p><p>I plan a series of articles, where we will build up the code base step-by-step and cover such issues as circular dependencies, lifecycles, lazy loading and container decomposition.</p><p>Are you ready? Let’s move on! 🏎</p><p>For a start, let’s make up an approximate plan of what we get throughout the series. So far, I have a clear understanding of what we have in the beginning and some vague ideas of what we’ll get in the end. Just keep it in mind.</p><p><strong>Contents of Article №1</strong></p><ul><li>Dependency Injection</li><li>Types of Dependencies</li><li>The Project: Writing a Container and Making Sure it Copes Well</li><li>Results of Part 1</li></ul><p>What we’ll cover in other articles:</p><ul><li>Dependency Lifecycle and How to Manage it</li><li>Container decomposition, circular dependencies</li><li>Lazy initialization</li><li>Let’s try to get rid of the boilerplate code when creating objects</li><li>Project Modularization</li></ul><p>If any ideas occur to me, or the community offers other requests when writing the articles, I can turn on a dime. I really enjoy this kind of flexibility 👌</p><p>For start, let’s clarify how we understand the Dependency Injection principle. Let’s begin with terminology.</p><h3>Dependency Injection</h3><p>💡In my understanding, <strong>dependency</strong> for a certain object is any external entity that helps this object do what it should.</p><p>For example, you have two screens: a list and details view: ListViewController and DetailsViewController. Let’s say ListViewControllerходит retrieves data from the backend, and ItemService helps in doing it. This is a <em>dependency</em>.</p><p>Besides, not to get trapped by the Massive View Controller, we moved the business logic away to ListPresenter. This is also a dependency. If we open DetailsViewController transferring the list element id to it, id is also a dependency. So…</p><p>💡<strong>Dependency Injection</strong> is a pattern that offers to implement all dependencies from the outside, and not to initialize them inside the object itself.</p><p>We can use a variety of techniques to do that, but today we’ll focus on one of them: implementing through the constructor in the init() method. What do we need it for? To ensure <em>independence</em>. Funny word play, eh? Independence of the object upon its dependencies: if they come from the outside, we can replace them with anything else any time. For example, with test mocks. Or with a red-button implementation instead of a blue button in A/B test.</p><h3>Types of Dependencies</h3><p>1️⃣<br>The data available only in the runtime.</p><p><em>Example:</em> id of the element from the list. No matter what method of dependency delivery we choose — with or without DI — we deliver them from the outside, as there are no dependencies and they can’t appear inside.</p><p>2️⃣<br>What we can create when initializing the object.</p><p><em>Example:</em> ListPresenter. Let’s say, we have the VIPER architecture and ListAssembly that assembles the entire VIPER module. It’s possible to create entities of this module simultaneously and to set connections between them, as all of them are destined to live simultaneously and no other way.</p><p>3️⃣<br>Dependencies the object shouldn’t know much about. It’s for their sake that the Dependency container pattern appeared.</p><p><em>Example:</em> ItemService. ListAssembly can claim that it needs ItemService, but it probably doesn’t know, how to create it itself. It’s because ItemService dependencies — for example, HttpClient or Repository to access the database — are beyond the area of responsibility of a certain screen.</p><p>Agree? Then let’s move on and get acquainted with the project.</p><h3>The Project</h3><p>So far I have only two screens. I am sure you know what they are! List and Details.</p><p>So far, it doesn’t really matter what entities are included in this list, and what data the Details screen shows. The important point is that we really get the data with ItemService that retrieves it from the database. I haven’t yet connected the backend. And, of course, I jump into the hype train and write all of this on SwiftUI. It may seem to you that I am not really good at SwiftUI, but I think I’ll become a guru by the end of the series of these articles. Let’s see ☝️👀️</p><p>The architecture of my project is MVVM. With routers. Don’t ask. I just wanted to show in living color that sometimes dependencies must be created together with the object, and it’s the best thing I could think of. I believe I still have a chance to invent a better example.</p><p>Thus, this is how it looks like:</p><pre>-- MyApp.swift<br>-- Model<br>  |-- Item.swift<br>-- Persistence<br>  |-- PersistenceController.swift<br>-- Service<br>  |-- ItemService.swift<br>-- Views<br>  |-- List<br>    |-- ListAssembly.swift<br>    |-- ListViewModel.swift<br>    |-- ListView.swift<br>    |-- ListRouter.swift<br>  |-- Details<br>    |-- DetailsAssembly.swift<br>    |-- DetailsViewModel.swift<br>    |-- DetailsView.swift</pre><p>Now, a couple of words about responsibility of the entities:</p><ul><li>Assembly is a screen builder. Its task is to return the View so that someone from the outside could display it. In between, it collects all dependencies for the View.</li><li>ViewModel stores the state, accepts events from View, and updates the state.</li><li>View — what can you say? It’s self-explanatory.</li><li>Router is a somewhat dwindled entity in the SwiftUI context, but I still don’t quite understand how to make navigation beautifully. In this project, we need it to illustrate work with the container. It’s in charge of getting the View to display the following screen.</li></ul><p>And some code:</p><pre>@MainActor<br>final class ListAssembly {<br>    func view() -&gt; ListView {<br>        let service = ItemService(persistence: PersistenceController.shared)<br>        let router = ListRouterImpl()<br>        let viewModel = ListViewModel(service: service, router: router)<br>        return ListView(viewModel: viewModel)<br>    }<br>}</pre><p>As you see, I already have DI: Both ListView and ListViewModel get their own dependencies in the constructor. For the context — ListView, ListViewModel and ListRouter code:</p><pre>struct ListView: View {<br><br>    @ObservedObject private var viewModel: ListViewModel<br><br>    init(viewModel: ListViewModel) {<br>        self.viewModel = viewModel<br>    }<br><br>    var body: some View {<br>        NavigationView {<br>            List {<br>                ForEach(viewModel.items) { item in<br>                    NavigationLink {<br>                        viewModel.detailView(by: item.id)<br>                    } label: {<br>                        Text(item.text)<br>                    }<br>                }<br>            }<br>        }<br>    }</pre><p>A simple screen with a table. Please note how View and ViewModel interact:</p><pre>@MainActor<br>final class ListViewModel: ObservableObject {<br>    struct Item: Identifiable {<br>      let id: Int<br>      let text: String<br>    }<br><br>    @Published var items: [Item] = []<br><br>    private let service: ListService<br>    private let router: ListRouter<br> <br>    init(service: ListService, router: ListRouter) {<br>        self.service = service<br>        self.router = router<br>        Task {<br>            do {<br>                items = try await service.items().enumerated().map { index, item in<br>                    Item(id: index, text: itemFormatter.string(from: item.timestamp))<br>                }<br>            } catch {<br>                print(&quot;No items&quot;)<br>            }<br>        }<br>    }<br><br>    func detailsView(by id: Int) -&gt; DetailsView? {<br>        guard let item = items.first(where: { $0.id == id }) else { return nil }<br>        return router.detailsView(with: item.text)<br>    }<br>}</pre><p>ViewModel can do three things: get data from ItemService, save them in the items array and return the DetailsView instance through accessing ListRouter:</p><pre>@MainActor<br>protocol ListRouter {<br>    func detailsView(with text: String) -&gt; DetailsView<br>}<br><br>@MainActor<br>final class ListRouterImpl: ObservableObject {}<br><br>extension ListRouterImpl: ListRouter {<br>    func detailsView(with text: String) -&gt; DetailsView {<br>      return DetailsAssembly(text: text).view()<br>    }<br>}</pre><p>So far, ListRouter creates the DetailsAssembly instance by itself.</p><p>And this is how the first screen is opened:</p><pre>@main<br>struct MyApp: App {<br>    var body: some Scene {<br>        WindowGroup {<br>            ListAssembly().view()<br>        }<br>    }<br>}</pre><p><strong>The main issue of this code</strong> is that the Assembly of a certain screen creates a service instance.</p><p>If, right now, DetailsViewModel needs to download the data with ItemService for detailed display (which is quite probable), DetailsAssembly will have the same string:</p><pre>let service = ItemService(persistence: PersistenceController.shared)</pre><p>Not to mention that we have to use PersistenceController singleton, so that both ItemService instances would have one and the same PersistenceController instance. And if we imagine that we add a new abstraction layer between the service and the base — ItemRepository? Now we’ll have to write the following in two places:</p><pre>let repository = ItemRepository(persistence: PersistenceController.shared)<br>let service = ItemService(repository: repository)</pre><p>And now let’s imagine that we have ten screens instead of two. And what if we have more abstraction layers?</p><p>I suggest resolving this issue with the <em>Dependency container</em>.</p><p><strong>Dependency container</strong> is the entity that delivers external dependencies. The container decides, if (and when) it is necessary to create a new instance, to store intense or subtle references. The entire dependency logic is encapsulated in it.</p><p>Now Assembly will get the input data that appear only in the runtime (dependencies of the first type in the beginning of the article), create instances of View, ViewModel and Router (dependencies of the second type) and request from the container the entities, whose creation the screen is not supposed to be aware of, for example, services (dependencies of the third type).</p><p>Since so far we have only one container — AppContainer — it will have no dependencies of the third type. It will know about all entities. Respectively, the container will get the input dependencies of the first type, and create dependencies of other types. Its first task will be to create ListAssembly to exclude its creation from MyApp.swift:</p><pre>@MainActor<br>final class AppContainer: ObservableObject {<br>    func makeListAssembly() -&gt; ListAssembly {<br>      ListAssembly()<br>    }<br>}</pre><p>Quite a simple code. Now we need to teach ListAssembly to request ItemService from AppContainer.</p><p>Let’s work in reverse order: first request dependencies, and then implement their delivery to make sure that the compiler helps us at every stage.</p><p>And here’s another important point: I don’t want ListAssembly to be able to request something extra from AppContainer, that’s why we will hide it under the protocol.</p><pre>protocol ListContainer {<br>    func makeItemService() -&gt; ItemService<br>}<br><br>@MainActor<br>final class ListAssembly {<br>    private let container: ListContainer<br><br>    init(container: ListContainer) {<br>        self.container = container<br>    }<br><br>    func view() -&gt; ListView {<br>        let service = container.makeListService()<br>        let router = ListRouterImpl()<br>        let viewModel = ListViewModel(service: service, router: router)<br>        return ListView(viewModel: viewModel)<br>    }<br>}</pre><p>Great! Nothing is built. The compiler says that we haven’t transferred a new dependency — ListContainer — to the ListAssembly constructor. Let’s correct it:</p><pre>func makeListAssembly() -&gt; ListAssembly {<br>   ListAssembly(container: self)<br>}</pre><p>Now the compiler reprimands us that AppContainer does not correspond to the ListContainer protocol. Let’s correct it:</p><pre>extension AppContainer: ListContainer {<br>    func makeItemService() -&gt; ItemService {<br>        ItemServiceImpl(persistence: PersistenceController.shared)<br>    }<br>}</pre><p>But wait a second! Now we have a container, and we don’t have to use PersistenceController singleton. Let the PersistenceController instance be stored in AppContainer as well:</p><pre>@MainActor<br>final class AppContainer: ObservableObject {<br>    private let persistenceController = PersistenceController()<br><br>    func makeListAssembly() -&gt; ListAssembly {<br>        ListAssembly()<br>    }<br>}<br><br>extension AppContainer: ListContainer {<br>    func makeItemService() -&gt; ItemService {<br>        ItemServiceImpl(persistence: persistenceController)<br>    }<br>}</pre><p>Great! Everything works fine. Now we need to get rid of explicitly creating DetailsAssembly in the list router:</p><pre>@MainActor<br>final class ListRouterImpl: ObservableObject {<br>    private let container: ListContainer<br><br>    init(container: ListContainer) {<br>        self.container = container<br>    }<br>}<br><br>extension ListRouterImpl: ListRouter {<br>    func detailsView(with text: String) -&gt; DetailsView {<br>        return container.makeDetailsAssembly(text: text).view()<br>    }<br>}</pre><p>The compiler is angry again. Let’s correct:</p><pre>protocol ListContainer {<br>    func makeItemService() -&gt; ItemService<br>    func makeDetailsAssembly(text: String) -&gt; DetailsAssembly<br>}<br><br>@MainActor<br>final class ListAssembly {<br>    private let container: ListContainer<br><br>    init(container: ListContainer) {<br>        self.container = container<br>    }<br><br>    func view() -&gt; ListView {<br>        let service = container.makeListService()<br>        let router = ListRouterImpl(container: container)<br>        let viewModel = ListViewModel(service: service, router: router)<br>        return ListView(viewModel: viewModel)<br>    }<br>}</pre><pre>extension AppContainer: ListContainer {<br>    func makeItemService() -&gt; ItemService {<br>        ItemServiceImpl(persistence: persistenceController)<br>    }<br><br>    func makeDetailsAssembly(text: String) -&gt; DetailsAssembly {<br>        DetailsAssembly(container: self, text: text)<br>    }<br>}</pre><p>So far, DetailsAssembly depends on ListContainer, but I will correct it in future articles of this series, when we consider container decomposition. The most important thing we’ve got is the opportunity to reduce creation of ItemService instance to one place, while it’s used in many places.</p><h3>Results of Part 1</h3><ul><li>We have set the general context for the articles: what dependencies are, what types of dependencies exist and what the Dependency Injection is. These definitions are my interpretation for general understanding of future content</li><li>Based on the example, we have discovered the danger of creating dependencies of the third type right before creating the object that depends on them</li><li>We used the Dependency container pattern we hid under the protocol and learned to request dependencies of the third type</li></ul><p>In the next article, I’ll continue to develop the container. We’ll see what we can teach it in the larger project.</p><p>Stay tuned! 🤘📲</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c076daf107bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/create-a-type-safe-dependency-injection-container-for-an-ios-application-part-1-c076daf107bc">Create a type-safe Dependency Injection Container for an iOS application. Part 1</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why is it so Convenient to Use the MVI Pattern in KMM]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/why-is-it-so-convenient-to-use-the-mvi-pattern-in-kmm-60563b18b061?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/60563b18b061</guid>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[android-development]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <dc:creator><![CDATA[Stefan Serkhir]]></dc:creator>
            <pubDate>Thu, 22 Jun 2023 11:46:54 GMT</pubDate>
            <atom:updated>2025-04-02T07:21:02.724Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7Lmyln0lNP6COCT9Se8aFg.png" /></figure><p>Hi!</p><p>My name is Stefan Serkhir. I am a mobile developer at <a href="https://www.lonto.io/">Lonto</a>. I code for Android, iOS, and KMM (Kotlin Multiplatform Mobile) and teach courses.</p><p>The MVI approach at KMM is very convenient because:</p><ul><li>It is easy to share business logic across all platforms</li><li>You can extract separate functionality to the feature modules</li><li>MVI itself allows you to easily divide the screen into different states and change them depending on the user’s actions</li><li>It is very easy to put MVI on Jetpack Compose (Android) and SwiftUi (iOS)</li></ul><p>From this article you will know:</p><ul><li><strong>What is MVI</strong></li><li><strong>Pros and cons of MVI</strong></li><li><strong>What is KMM</strong></li><li><strong>MVI in KMM — practice</strong></li><li><em>How the project looks like from the Android side:</em></li><li>MainScreen</li><li>MainViewModel</li><li>MainStore</li><li>StoreFactory</li><li>Executor</li><li>Reducer</li><li><em>How the project looks like from the iOS side:</em></li><li>MainViewController</li><li>MainView</li><li><strong>Common code in Shared</strong></li><li><strong>Conclusion on the MVI in KMM</strong></li></ul><h3>What is MVI</h3><p><strong>MVI (Model-View-Intent)</strong> is an architectural pattern that is based on the idea of Unidirectional Data Flow and fits well with declarative UI frameworks such as Compose on Android and SwiftUI on iOS. MVI has several implementations: MVICore, MVIKotlin, Mosby, and many more. Some of them are multiplatform, that is they support KMP (Kotlin Multiplatform).</p><p>Historically, the roots of MVI stretch back to the Web, but today they are well used in Flutter (BLoC), for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*38h9E4phTHfo981lmqIbOA.jpeg" /></figure><p>So we have the UI (our View) which is what users see. The essence of MVI is that users can interact with the View with special intents, and in our case it means the intention of users to take an action in the UI.</p><p>The intent is sent to the so-called black box, which processes it and returns the new state outside — it updates the model. Since the View is subscribed to this state, it receives it and renders a new one.</p><p>In the end, the UI has only one responsibility: to draw the current state. That is, our View contains no logic.</p><p>This black box is usually called the MVI-Feature, and the way it converts one state to another is called business logic.</p><h3>Pros and cons of MVI</h3><p><strong>Pros:</strong></p><ul><li>Integrates well with declarative UI frameworks such as Compose and SwiftUI</li><li>One single state which is drawn in the View</li><li>The state changes in one place. This makes it easy to debug, and you can’t see a non-consistent state on the screen. That is, we always see one particular state</li></ul><p><strong>Cons:</strong></p><ul><li>Boilerplate</li><li>You need to count the diff (difference, changes) of the state and redraw the changes only</li></ul><p>The state can be large on a complex screen, e.g. there can be 15 fields there. If you don’t count the diff, but redraw the whole screen every time the state is refreshed, the UI can be laggy… To do this, you need to count the state’s diff and redraw the changes only.</p><h3>What is KMM</h3><p><strong>KMM (Kotlin Multiplatform Mobile)</strong> is a subset of Kotlin Multiplatform.</p><p><strong>Kotlin Multiplatform</strong> is a technology that allows you to write code in Kotlin language for multiple platforms, or — in KMP terms — targets. Targets can be any popular platform, such as desktop: Linux, MacOS, Windows. If we talk about mobile operating systems, it’s Android and iOS. One recent update is that Aurora OS is now <a href="https://t.me/mobiledevnews/1341">supported</a>.</p><p>The Kotlin Multiplatform also supports the Web and smartwatch operating systems, such as watchOS.</p><p>In this article we will check out the KMM specifically. We will have two targets: Android and iOS. We will also focus on how MVI works with these two platforms.</p><p>In our project, we have two apps on iOS and Android with a native code. At the same time, these platforms depend on the shared code (also called the common code). The common code can contain business logic, basic stuff about dealing with networks or database, and complex calculations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b037lSt4XeASNRXhwpIAiA.jpeg" /></figure><p>There can also be platform-specific code in the common part. In the KMM case, these are iOS- and Android-specific APIs and classes. This is an advantage of KMM because it allows you to cover platform stuff with “interfaces” using the expect/actual mechanism. We discussed the implementation examples in the <a href="https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50">KMM Through the Eyes of an iOS Developer</a> article.</p><p>Let’s check out the project to see how it all works.</p><h3>MVI in KMM — practice</h3><p>Let’s look at MVI in practice. You can find an example of the project on <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample">GitHub</a>.</p><p>In this project, we have two apps: iOS and Android. They have one screen and a simple interface shown above.</p><p>In these apps, we can load information about the user: name, surname, date of birth, gender, and type of device. There is also one “Upload” button. If you tap it, you get the loading screen.</p><p>We may also have an error, and the app will notify us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlaMSNKQR_POrZlXyqWg_w.jpeg" /></figure><p>In this case we can reboot. And eventually we will be able to get our data.</p><p>The apps have no navigation, but only one screen and one MVI Feature. Under the hood, both iOS and Android apps use KMM and MVI (the implementation is <a href="https://arkivanov.github.io/MVIKotlin/">MVIKotlin</a>).</p><p>Now let’s look at the source code of this project. If you use Android Studio or IntelliJ IDEA, you should select the project view as Project to see all the source code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-psuwStM872bf1J2Gyao9A.jpeg" /></figure><p>First of all, we want to see the folders in the root of the project: <em>androidApp</em>, <em>iosApp</em>, and <em>shared</em>. They have the app’s source code. The <em>androidApp</em> contains code for Android, the <em>iosApp</em> contains code for iOS, and the <em>shared</em> contains common code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwDl42DmYItXYeRi0YkjHQ.jpeg" /></figure><h3><strong>How the project looks like from the Android side</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ejX0F1fs3hPlucumKBfetA.jpeg" /></figure><p>We’ve got one <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/androidApp/src/main/java/ru/kts/mobile/sample/android/MainActivity.kt">MainActivity</a> here. We should find the <em>private val viewModel by viewModel&lt;MainViewModel&gt;()</em> string and inject <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/presentation/MainViewModel.kt">ViewModel</a> there. And we collect the dependency graph in onCreate for simplicity:</p><pre>override fun onCreate(savedInstanceState: Bundle?) {<br>    super.onCreate(savedInstanceState)<br><br>    initKoin {<br>        androidContext(applicationContext)<br>    }<br>}</pre><p>This is also where <em>setContent</em> is called, in which we describe our Views. In our case, the UI is written in Compose:</p><pre>setContent {<br>    val state by viewModel.state.collectAsState()<br><br>    MainScreen(<br>        state = state,<br>        onLoadClick = viewModel::load,<br>    )<br>}</pre><p>This call is similar to the usual setContent call, to which we pass the layout file. This is the usual extension that wraps Composable into a Compose view, a special View for Composable.</p><p>Inside <em>setContent</em> we do the following:</p><ol><li>We subscribe to the state that comes from the ViewModel by calling the <em>collectAsState</em> (but it is better to do it with <em>collectAsStateWithLifecycle</em>). This is important because we work with Compose, in which it is better to operate with the state, not just with Flow or RX entities.</li><li>We call the <em>MainScreen</em> Composable function. This is a usual Composable function, to which we pass the state and the load click event to our ViewModel. In this case, <em>viewModel::load</em> is a reference to the <em>load</em> method of ViewModel. We’ll discuss what’s in there a bit later.</li></ol><h4>MainScreen</h4><p>If we go to the <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/androidApp/src/main/java/ru/kts/mobile/sample/android/ui/MainScreen.kt">MainScreen</a>, we see <em>when</em> with three branches:</p><pre>when {<br>    state.error -&gt; ErrorState(<br>        modifier = Modifier<br>            .align(Alignment.Center),<br>        onLoadClick = onLoadClick,<br>    )<br>    state.loading -&gt; CircularProgressIndicator(<br>        modifier = Modifier<br>            .align(Alignment.Center),<br>        color = buttonPrimaryActiveColor,<br>        strokeWidth = 3.dp,<br>    )<br>    userInfo != null -&gt; UserInfoDetails(<br>        modifier = Modifier<br>            .align(Alignment.Center),<br>        userInfo = userInfo,<br>        onLoadClick = onLoadClick,<br>    )<br>}</pre><p>Here we have three possible screen states:</p><ul><li><em>error</em>: the state with an error</li><li><em>loading</em>: loading state</li><li><em>userInfo</em>: the state of the screen when we have data and display it</li></ul><p>In larger projects we will have utilities written for this, so the code will look prettier. But we have a simplified example, so in this case it looks like this.</p><p>This is how the View draws the states: we have <em>when</em> with all possible states of the screen. And for each possible state of the screen a certain state is drawn. You can easily do this in Compose.</p><p>If you go back to MainActivity, you’ll see that the state comes from ViewModel. So let’s look at what we have there.</p><h4>MainViewModel</h4><p>In the constructor we have two private properties:</p><ul><li><em>store</em> is an MVI Feature</li><li><em>stateMapper</em> which maps the domain state to UiMainState</li></ul><pre>class MainViewModel(<br>    private val store: MainStore,<br>    private val stateMapper: Mapper&lt;MainStore.State, UiMainState&gt;,<br>)</pre><p>Ideally, the View should operate on the <em>UiState</em> and not on the domain state, since it should not know what is happening in our domain area.</p><p>In ViewModel we are interested in the public members of the class:</p><ul><li>The state property, which is declared with the <em>CStateFlow</em> type (we will tell about the first letter <em>C</em> in the name later), and the type of our state (<em>UIMainState</em>) is: <em>val state: CStateFlow&lt;UiMainState&gt;</em>. The state property represents the state to which the View is subscribed.</li><li>The <em>load: fun load() = store.accept(MainStore.Intent.Load)</em> method. This method proxies the event to the MVI Feature. In this case it is a loading event. To send this intent to the MVI Feature, we call the accept method and drop the desired intent there. In our case it is <em>MainStore.Intent.Load</em>.</li></ul><p>It is important to understand that the ViewModel should take the <em>UiState</em> from the Store. So in the <em>init</em> block we call the <em>bindAndStart</em>:</p><pre>init {<br>    bindAndStart {<br>        store.states.map(stateMapper::map) bindTo (::acceptState)<br>    }<br>    load()<br>}</pre><p>Inside the lambda of this method the following things happen:</p><ol><li>We take our <em>store</em> and the states it produces</li><li>We map them to the <em>UiState</em> using the <em>stateMapper</em>, which maps from the domain state to the <em>UiState</em></li><li>We bind these states to a method — to <em>acceptState</em> in our case</li><li>Inside the <em>acceptState</em> method, we put the UI state into the <em>mutableState</em> — a private field of the <em>MutableStateFlow&lt;UiMainState&gt;</em> type</li></ol><p>As a result, our state is obtained from the <em>mutableState</em>, which we first convert to the <em>CStateFlow</em> type by calling the <em>cStateFlow()</em> extension.</p><p>As we’ve noted earlier, we work with the <em>CStateFlow</em> type, not just the <em>StateFlow</em> type. The point is that this is not the Android’s ViewModel, but the KMM’s <a href="https://github.com/icerockdev/moko-mvvm">ViewModel</a>. It is located in the shared module, in the <em>commonMain</em>. And this ViewModel is shared between iOS and Android.</p><p>In Kotlin, interfaces support generics. And it is in Kotlin, where <em>StateFlow</em> is represented as an interface. You can read about the nuances of Kotlin and Swift interoperability in our <a href="https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50">KMM Through the Eyes of an iOS Developer </a>article.</p><p>That said, Swift also has interfaces. They are called protocols. But interfaces in Swift do not support generics, which is why we wrap our usual coroutine <em>StateFlow</em> in a utilitie called <em>CStateFlow</em>.</p><p>When the Kotlin code is compiled into Objective-C for iOS, you get the <em>CStateFlow</em> class there. And Swift classes can contain generics. So it’s just a utilitie for iOS compatibility. But it is essentially the same <em>StateFlow</em>.</p><p>We’ve described the ViewModel, and now we can go even deeper and get into our Store — specifically the MainStore declaration.</p><h4>MainStore</h4><p>This is a <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/domain/api/MainStore.kt">standard interface</a> that inherits the Store interface.</p><p><strong>The Store interface</strong> is a base interface from the Kotlin MVI library. When we work with Kotlin MVI, it is inherited from the base Store and gives three generics to the base Store:</p><pre>interface MainStore : Store&lt;MainStore.Intent, MainStore.State, Nothing&gt;</pre><ul><li><em>MainStore.Intent</em> are the types of intents that can be sent to our feature — to the black box</li><li><em>MainStore.State</em> is the type of the state that the feature gives to the outside</li><li><em>Nothing</em> is a type of a label In our case we have no labels, so it’s Nothing</li></ul><p>MVI is good because it allows you to draw one particular state. In our case, labels are used for one-time events, like displaying a toast or a dialog, or performing navigation. That is, these are single-use things that should not be in the common state.</p><p>In our particular example, there are no labels because there is no navigation or a toast with an error.</p><p>Two entities are declared inside the interface itself:</p><p>1. Domain state:</p><pre>data class State internal constructor(<br>    val details: UserInfo? = null,<br>    val isLoading: Boolean = false,<br>    val isError: Boolean = false,<br>)</pre><p>It has three properties:</p><ul><li><em>details</em> — information about the user</li><li><em>isLoading</em> — shows whether the loading is in progress</li><li><em>isError</em> — shows if we’ve got an error</li></ul><p>In large projects, the <em>StringMessage</em> (for example) will be used instead of the <em>Boolean</em> type in <em>isError</em>. It’s because there are various errors in the business logic, and they are handled differently depending on the type of the error (roughly speaking, the type of the exception). And one <em>Boolean</em> is not enough for different types of errors.</p><p>2. Declaration of intents:</p><pre>sealed interface Intent {<br>    object Load : Intent<br>}</pre><p>Here we define the type of intents that can be sent to our feature.</p><p>In this case, we have only one intent: the <em>Load</em>. It is the loading intent. That said, there could have been another intent here, such as a refresh or text entry.</p><p>Usually intents are declared as <em>sealed</em> interfaces or <em>sealed</em> classes, because that way it is convenient to process them in the feature itself.</p><p>As a result, the <em>MainStore</em> interface is essentially a business logic API. There are no implementation details here. What we have is just a description of a state that our feature operates on. We also have descriptions of intents that this feature can accept.</p><p>The implementation of the business logic itself is in the <em>MainExecutor</em>, with an addition of <em>MainReducer</em> and <em>MainStoreFactory</em>. Let’s take a closer look at them.</p><p><strong>StoreFactory</strong></p><p>Since the feature is presented as an interface, we should create its implementation. To do this, we have <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/domain/impl/MainStoreFactory.kt">StoreFactory</a> which allows you to create an instance of the MVI feature.</p><p>Usually all <em>StoreFactory</em> are very simple: they have one create type method only:</p><pre>fun create(): MainStore = object :<br>    MainStore,<br>    Store&lt;MainStore.Intent, MainStore.State, Nothing&gt; by storeFactory.create(<br>        name = MainStore::class.simpleName,<br>        initialState = MainStore.State(),<br>        bootstrapper = null,<br>        executorFactory = {<br>            MainExecutor(<br>                repository = repository,<br>            )<br>        },<br>        reducer = MainReducer(),<br>    ) {}</pre><p>The <em>create()</em> method creates an Object that inherits the <em>MainStore</em> interface and uses a kotlin delegate to create an implementation of our Store.</p><p>In addition to creation, usually Messages are described in <em>StoreFactory</em>. But you can also do it elsewhere: there are no limitations here. For example, you can describe the Store in one file, the intents in a second, and the state in a third. But it’s better to have it all coherent and kept in one place.</p><p>In our case, the <em>MainStoreFactory</em> describes the <em>sealed interface</em> <em>Message</em>:</p><pre>sealed interface Message {<br>    object SetLoading : Message<br>    data class SetUserInfo(val userInfo: UserInfo) : Message<br>    object SetError : Message<br>}</pre><p>This is an important point in the context of MVI, and we will also discuss it later.</p><p>Let’s recall that Store is created using the <em>StoreFactory</em> delegate. When we create this MVI feature, we can set some default behavior for it. For example, we want all of our MVI features to log the events that come into them, and the states they produce after those events. To do this, you need to define a base <em>StoreFactory</em>, which will contain this behavior.</p><p>If we go to the DI module (<a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/di/MainModule.kt">mainModule</a>), where <em>StoreFactory</em> is created, we see that it is created based on the <em>LoggingStoreFactory</em>. If you look at the name, you can see that the <em>LoggingStoreFactory</em> simply logs the events of the feature. Herewith the implementation of the logger can be anything, in our case it is <a href="https://github.com/AAkira/Napier">Napier</a>.</p><p>There are several ready-made implementations of the <em>StoreFactory</em> in the MVIKotlin library. You are free to choose the best implementation for your needs. There is also a default implementation that does nothing: it does not impose behavior.</p><p>Usually 100% of the time you use <a href="https://github.com/arkivanov/MVIKotlin/blob/master/mvikotlin-logging/src/commonMain/kotlin/com/arkivanov/mvikotlin/logging/store/LoggingStoreFactory.kt">LoggingStoreFactory</a> at a minimum. It allows you to log what happens inside the MVI feature. This helps with debugging an app, for example.</p><p>So, we’ve learnt what the <em>MainStoreFactory</em> is. Now let’s talk about the <em>Executor</em>, which contains most of the business logic.</p><h4>Executor</h4><p>A black box core that takes intents, does something with them, processes them, and outputs a new state. It contains the business logic of the app, passages through the repository to the network, databases, and calculations.</p><p>In our project, the <em>Executor</em> is called the <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/domain/impl/MainExecutor.kt">MainExecutor</a>. It inherits the base <em>Executor</em>.</p><p>The base <em>Executor</em> in this case simply wraps the methods from the library <em>Executor</em> in <em>scope.launch</em>:</p><pre>final override fun executeIntent(intent: Intent, getState: () -&gt; State) {<br>    scope.launch {<br>        suspendExecuteIntent(intent, getState)<br>    }<br>}<br><br>final override fun executeAction(action: Action, getState: () -&gt; State) {<br>    scope.launch {<br>        suspendExecuteAction(action, getState)<br>    }<br>}</pre><p>You need it so that you don’t have to wrap suspend-calls in <em>scope.launch</em> every time.</p><p>By default, <em>scope</em> in the <em>Executor</em> runs on the main thread because the state change must be in one thread. But coroutines let you easily do heavy or IO operations in other threads. It is also important to understand that the <em>dispose</em> of a feature cancels its <em>scope</em>, so we highly recommend to use cancelable suspend calls. Thus, because of the structured concurrency in Kotlin coroutines, all our operations within the scope will also be canceled. <a href="https://www.wwdcnotes.com/notes/wwdc21/10134/">This concept is conveniently implemented in iOS at the Swift language level.</a></p><p>We also have generics here that are given to the base <em>Executor</em>:</p><pre>internal abstract class BaseExecutor&lt;in Intent : Any, in Action : Any, in State : Any, Message : Any, Label : Any&gt;(<br>    mainContext: CoroutineContext = Dispatchers.Main,<br>) : CoroutineExecutor&lt;Intent, Action, State, Message, Label&gt;(mainContext = mainContext) {</pre><p>There are five generics here:</p><ul><li><em>Intent</em>: what the user sends to the feature</li><li><em>Action</em>: internal actions</li><li><em>State</em>: the state that the feature operates on</li><li><em>Message</em>: the result of processing the intent. Using it, the Reducer (we’ll talk about it later) will create a new state</li><li><em>Label</em>: a one-time event</li></ul><p>And what about that new gimmick — the <em>Action</em>? So, let’s say we have an app with a UI. The user can interact with this app, i.e. they can send intents to the feature. But sometimes you need to interact with a feature not from the outside, but from the inside.</p><p><strong>External interaction</strong> is when a user performs an action and an intent is sent.<br><strong>Internal Interaction</strong>. The example is when we need to stop network connection attempts when there’s no network. Instead, we need to go directly to the local database, so as not to waste resources and memory.</p><p>For such cases we have the <em>Action</em>. These are internal actions that we can send to our feature. They are used quite rarely, but they can be useful.</p><p>We also have the interesting suspendExecuteIntent method in the <em>MainExecutor</em>. It is defined from the base Executor. In this method, we accept the intents that the user sends to the black box.</p><p>The method signature contains the <em>intent</em> parameter and the <em>getState</em> lambda:</p><pre>override suspend fun suspendExecuteIntent(<br>    intent: MainStore.Intent,<br>    getState: () -&gt; MainStore.State,<br>) = when (intent) {<br>    is MainStore.Intent.Load -&gt; loadUserInfo()<br>}</pre><p><em>getState</em> is a lambda to be called. It will bring the current state back to us.</p><p>If we would have <em>state: MainStore.State</em> instead of <em>getState: () -&gt; MainStore</em>, then a link to a specific <em>State</em> object would come. In this case, we would not be able to get the actual state of the feature. That’s why it’s done as a lambda which allows you to get the named current state at the moment the lambda is called.</p><p>We keep going through the code and take <em>when</em> from the <em>Intent</em>. Since <em>Intent</em> is a <em>sealed</em> interface with one subclass, we can only have one branch — the <em>Load</em>. In it, we call the <em>loadUserInfo()</em> method.</p><p>In the next method we dispatch the <em>Message.SetLoading</em>:</p><pre>when (val response = repository.getUserInfo()) {<br>    is Response.Success -&gt; dispatch(MainStoreFactory.Message.SetUserInfo(response.data))<br>    is Response.Failed -&gt; dispatch(MainStoreFactory.Message.SetError)<br>}</pre><p>The <em>MainExecutor</em> contains the business logic, but it does not convert the current state to a new one. The <em>Reducer</em> entity is responsible for converting a state from the old to the new one after some business logic actions. We need it so that the <em>Executor</em> contains the business logic only. So everything the <em>Executor</em> does is dispatching the <em>Message.SetLoading</em>.</p><p>The <em>Reducer</em>, which we’ll talk about later, takes these <em>Messages</em>, takes the old state, and transforms it into the new one based on these <em>Messages</em>. And the feature will then release that state outside.</p><p>So, we actually say that we need to set the load state at the beginning of the <em>loadUserInfo</em> method. Then we go to the repository and get information about the user.</p><p>The <em>getUserInfo</em> method returns a utilitie in the form of the <em>Response</em>. This is a basic utilitie that has two subclasses: <em>Success</em> and <em>Failed</em>.</p><p>In real projects in production, the repository will not always return the data. It may return an exception: for example, an error may occur. In this case, the data types are usually wrapped in some kind of a utilitie at the repository. Here, it’s the <em>Response</em> utilitie.</p><p>The result is two situations: successful and unsuccessful data collection. It turns out that <em>when</em> has two branches.</p><p>If we’ve successfully collected the data, we dispatch it: <em>Message.SetUserInfo(response.data))</em>. This Message goes to the Reducer, where it converts the old state to the new one. And when we have an error, we put an error: <em>Message.SetError</em>.</p><p>Now let’s look at the Reducer.</p><h4>Reducer</h4><p>Ordinary class. It is inherited from the base library <em>Reducer</em> which overrides one method — <em>reduce</em>. Let’s check out the <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/shared/src/commonMain/kotlin/ru/kts/mobile/sample/domain/impl/MainReducer.kt">MainReducer</a>:</p><pre>internal class MainReducer : Reducer&lt;MainStore.State, MainStoreFactory.Message&gt; {<br><br>    override fun MainStore.State.reduce(<br>        msg: MainStoreFactory.Message,<br>    ) = when (msg) {<br>        is MainStoreFactory.Message.SetError -&gt; copy(<br>            isError = true,<br>            isLoading = false,<br>        )<br>        is MainStoreFactory.Message.SetUserInfo -&gt; copy(<br>            details = msg.userInfo,<br>            isLoading = false,<br>        )<br>        is MainStoreFactory.Message.SetLoading -&gt; copy(<br>            isLoading = true,<br>            isError = false,<br>        )<br>    }<br>}</pre><p>The essence of the <em>reduce</em> method is to convert the old state into a new one. This is done using the <em>copy</em> method, which is important because our state <strong>should be</strong> immutable. So we copy our old state and change certain properties in it.</p><p>The <em>Message</em> that comes to the <em>Reducer</em> has been declared as a <em>sealed</em> interface. So we can take <em>when</em> in the <em>reduce</em> method from this <em>Message</em>. As a result, we will have three branches in which the state will be transformed: <em>SetError</em>, <em>SetUserInfo</em>, and <em>SetLoading</em>.</p><p><strong>One-time events</strong></p><p>We mentioned the <em>Label</em> above that is used for one-time events. Let’s check out how it works and display a toast.</p><p>Let’s say we have a Store and we want to add a label to it. To do this we write the following code:</p><pre>sealed interface Label {<br>    object Toast : Label<br>}</pre><p>The label is called the <em>object Toast</em>. We need to put it in a generic. After that, we go to the <em>Executor</em>, where we pass the <em>Label</em> instead of <em>Nothing</em>:</p><pre>internal class MainExecutor(<br>    private val repository: Repository,<br>) : BaseExecutor&lt;MainStore.Intent, Nothing, MainStore.State, MainStoreFactory.Message, MainStore.Label&gt;() {</pre><p>In addition to the fact that we are already displaying the error state on the screen, we also want to display a toast. Let’s write it this way:</p><pre>when (val response = repository.getUserInfo()) {<br>    is Response.Success -&gt; dispatch(MainStoreFactory.Message.SetUserInfo(response.data))<br>    is Response.Failed -&gt; {<br>           publish(MainStore.Label.Toast) // “публикуем” наш label<br>           dispatch(MainStoreFactory.Message.SetError)                <br>}</pre><p>We go back to ViewModel and subscribe to the labels at the feature.</p><pre>init {<br>    bindAndStart {<br>        store.states.map(stateMapper::map) bindTo ::acceptState<br>        store.labels. bindTo ::acceptState // в метод acceptState будут приходить label-ы<br>    }<br>    load()<br>}</pre><p>We bind the labels to some method, the <em>acceptLabel</em> in our case:</p><pre>private fun acceptLabel(label: MainStore.Label)  {<br>}</pre><p>Now the labels will come into the <em>ViewModel</em>, and we can handle them in the <em>acceptLabel</em> method.</p><p>Summary of what was done:</p><ol><li>We declared the label in the Store as <em>sealed</em> interface/class</li><li>We went to the entity’s MVI and put the label instead of <em>Nothing</em> in the generic</li><li>We called the <em>publish</em> and passed the label there</li><li>In ViewModel, we took labels from the Store and bound them</li><li>In the UI, we subscribe to labels by <em>viewModel.labels.collect { … }</em> type</li><li>We display our toasts</li></ol><p>Since we describe MVI in the context of KMM, we will check out how it all looks in iOS.</p><h3>How the project looks like from the iOS side</h3><p>To check out an iOS project, you need to open the repository in Xcode. Xcode is a development environment in which iOS apps are written. Two languages are used there: Objective-C and Swift. Objective-C is like Java and Swift is like Kotlin. Our example is written in the second one.</p><p>In iOS , among the main entities we can distinguish:</p><ul><li><em>MainViewController</em>, an analog of a fragment from Android</li><li><em>MainAssembly</em> is where dependencies are added, including the ViewModel from the Koin</li><li><em>MainView</em> is the root view of our controller</li></ul><p>Swift doesn’t really know anything about Koin, so in order to get dependencies from KMM and then use them in Swift code, we need to use some iOS DI. In our case we use the <a href="https://github.com/Swinject/Swinject">Swinject</a> library to make things simpler.</p><p>Let’s take a brief look at the <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/iosApp/App/Main/View/MainViewController.swift">MainViewController</a> and <a href="https://github.com/StefanSerkhir/MVI-KMM-Sample/blob/master/iosApp/App/Main/View/MainView.swift">MainView</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJxK-yLWz_yaiZcMNRItPQ.jpeg" /></figure><h4>MainViewController</h4><p>The <strong>UIViewController in iOS</strong> is essentially analogous to fragments in Android. Let’s look at its code:</p><pre>final class MainViewController: UIViewController {<br>    <br>    private let viewModel: MainViewModel<br>    <br>    …<br>    <br>    private func bindUI() {<br>        <br>        viewModel.state.subscribe { [weak self] state in<br>            guard let state = state, let self = self else { return }<br>            <br>            if state.error {<br>                self.mainView.updateState(.error)<br>            } else if state.loading {<br>                self.mainView.updateState(.loading)<br>            } else if let details = state.userInfo {<br>                self.mainView.updateState(.normal(userInfo: details))<br>            }<br>        }<br>    }<br>        <br>    …<br>}</pre><p>This is where the ViewModel is transferred with the help of <a href="https://github.com/Swinject/Swinject">Swinject</a>. And in the <em>bindUI</em> method, just like in Android, we subscribe to the states that come from the ViewModel. Then we update the MainView according to the received state.</p><h4>MainView</h4><p>The root View on our screen. This is analogous to MainScreen from Android. In it we use cases to show this or that state.</p><h3>Common code in Shared</h3><p>Let’s recall that you can share the business logic, the data layer with KMM. But you can also use KMM to share even more code.</p><p>If we look in the res folder in androidApp, we can see that there are no other resources apart from styles. There are no strings, colors, or fonts.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CXHw34m_lPH2CIp1JKyt8Q.jpeg" /></figure><p>In our example, we have shared the resources between iOS and Android, so they are in the shared, in <em>CommonMain</em>. From the resources you can share colors, strings, images, fonts, and the community already has several ready-made solutions. We use <a href="https://github.com/Skeptick/libres">libres</a> and <a href="https://github.com/icerockdev/moko-resources">MOKO</a> libraries from IceRock.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q95qT5hJYg86vk1GZXazow.jpeg" /></figure><p>The <strong>default</strong> resource structure in the KMM module</p><p>It is convenient when you work in a team. For example, if an iOS developer implements a feature, the Android developer won’t have to go to Figma, copy colors, strings, and images, download and convert them into Drawable XML files. In this case, the Android developer will only have to make up some UI, and all the logic and resources will be in the KMM.</p><p>This makes development cheaper, faster, and more enjoyable. Instead of having to breed these resources twice, they are created only once and are shared between platforms. Moreover, we essentially implement almost the same behavior on iOS and Android (except when it’s about platform peculiarities). And if there are bugs, they will most probably be common😁. But they will be fixed at once and in one place for both platforms.</p><p>The move to KMM changes almost nothing for the Android developer. We wrote about <a href="https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50">the iOS developers experience</a> earlier.</p><h3>Conclusion on the MVI in KMM</h3><p>We checked out MVI in KMM in practice and discovered how it looks in code from the Android and iOS side.</p><p>It helps to save time in the project, makes the development cheaper and more convenient.</p><p>Our project is small, but if you properly divide shared into modules, it can be easily scaled. The entry threshold for MVI is higher than for MVVM or MVP. For example, in the case of MVVM/MVP we would have only one additional entity — the ViewModel/Presenter. And with MVI we have three base entities, each with its own area of responsibility.</p><p>In my opinion, MVI is the most convenient architectural solution of the presentation layer, among those that the community has. It is because:</p><ul><li>The screen is always in one particular state</li><li>Easy to debug</li><li>The data goes in one direction, so it’s easy to track changes</li><li>Easy to reuse</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=60563b18b061" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/why-is-it-so-convenient-to-use-the-mvi-pattern-in-kmm-60563b18b061">Why is it so Convenient to Use the MVI Pattern in KMM</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[KMM Through iOS Developer’s Eyes]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/8c23cded1a50</guid>
            <category><![CDATA[kotlin-multiplatform]]></category>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[kmp]]></category>
            <dc:creator><![CDATA[Maxim  Myalkin]]></dc:creator>
            <pubDate>Wed, 07 Jun 2023 14:06:51 GMT</pubDate>
            <atom:updated>2025-04-02T07:22:43.244Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pDW5mPFl-qFbYK-_hxdYUA.png" /></figure><p>Hi! My name is Maxim Myalkin, I’m mobile teamlead at <a href="https://www.lonto.io/">Lonto</a>.</p><p>We use Kotlin Multiplatform Mobile (KMM) to share code across Android and iOS.</p><p>You can find a fair number of articles on this technology, but most of them are either about choosing a cross-platform technology or about a project transition to KMM.</p><p>I’d like to talk about our experience with KMM from the iOS development perspective. We’ll discuss the problems we encountered and their solutions, our development approach, and, most importantly, how iOS devs feel about this technology.</p><p><em>Content:</em></p><ul><li><strong>Context</strong></li><li><strong>Kotlin</strong></li><li><strong>Environment</strong></li><li><strong>Nuances with the use of KMM<br></strong> -Linking common code to an iOS project<br>- Where to store common code?<br>- Coroutines, Flow<br>- Native libraries in common<br>- Common libraries in native</li><li><strong>Implementing specific areas of the project<br>- </strong>DI<br>- Navigation<br>- Network<br>- UI</li><li><strong>Debugging an app</strong></li><li><strong>Crashes</strong></li><li><strong>Logging non-critical errors</strong></li><li><strong>Memory leaks</strong></li><li><strong>Process</strong></li><li><strong>Bottom line</strong></li></ul><h3>Context</h3><p><a href="https://kotlinlang.org/docs/multiplatform-mobile-getting-started.html">Kotlin Multiplatform Mobile</a> (KMM) is an SDK for multiplatform development from JetBrains. It allows you to bring reusable business logic into a module that is shared between iOS and Android platforms.</p><p>KMM’s alpha version was released in August 2020. The technology went into<a href="https://blog.jetbrains.com/kotlin/2022/10/kmm-beta/"> beta</a>. At the same time, Google <a href="https://android-developers.googleblog.com/2022/10/announcing-experimental-preview-of-jetpack-multiplatform-libraries.html">began migrating</a> Jetpack libraries to KMM.</p><p>Now we see that large companies use KMM in mobile apps more and more frequently. The examples are:</p><ul><li>QIWI</li><li>Profi</li><li>Leroy Merlin</li><li>AliExpress</li><li><a href="https://touchlab.co/kamp-kit-touchlab/">Touchlab</a></li><li><a href="https://medium.com/mcdonalds-technical-blog/mobile-multiplatform-development-at-mcdonalds-3b72c8d44ebc">McDonald’s</a></li></ul><p>Our team uses KMM to optimize the development and maintain existing code, which is especially important on projects with deadlines. I will not dive deep into why we’ve chosen it, but in short: KMM made it possible not to retrain our team, as it would have been if we had used Flutter.</p><p>Business logic and data handling are usually the same for Android and iOS. And KMM allows you to write code for two platforms at once and still keep the implementation of the UI native.</p><p>We put all platform-independent logic into the KMM module:</p><ul><li>network requests</li><li>data parsing</li><li>data storage</li><li>business logic: checking authorization, validation of entered data, changing the state of screens. We have business logic as an MVI feature written using MVIKoltin</li></ul><p>You can check out what other companies transfer to the cross-platform part in the <a href="https://blog.jetbrains.com/kotlin/2021/10/multiplatform-survey-q1-q2-2021/">JetBrains survey results</a>.</p><p>Using KMM does not change the Android development in any way, except for the networking and storage libraries part. Multi-module projects have already become a default in Android development. And the business logic is written in Kotlin without any platform dependencies and according to the clean architecture.</p><p>Still, there are nuances to implementing KMM in iOS development. We’ll talk about them later.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3YIN5uDg-75VVnfYi60OwQ.jpeg" /></figure><p>Not always iOS developers implement the KMM’s general functionality. But in our team we have not only Android, but also iOS developers who do it.</p><p>The first problem an iOS developer faces is a new language. Most of them have never worked with Kotlin. They work with Swift. In our team and according to feedback from other companies, iOS developers have had no difficulties understanding the Kotlin code. Kotlin and Swift are both modern and evolving programming languages, and there are many similarities between them.</p><p>What was unusual in the beginning:</p><ul><li>you cannot use the same method or class names within the same package, even if they are declared in different parts: common, iOS</li><li>expression chain and <a href="https://kotlinlang.org/docs/scope-functions.html">scope functions</a> are hard to read and use</li></ul><p>There are also nuances lurking at the Swift–Kotlin interop stage. Kotlin/JVM is used for Android and Kotlin/Native is used for iOS.</p><p>In most cases, these nuances are insignificant:</p><ul><li>unlike Swift, Kotlin has no checked exceptions. If the method throws an exception, the iOS part will crash. To avoid this, the method declaration must be annotated with <a href="https://habr.com/users/Throws">@Throws</a> (Exception::class). But we adhere to the approach where the Result wrapper is returned. That is, the method returns either success or fail, and no exception is ever thrown</li><li>extensions in Kotlin are <a href="https://kotlinlang.org/docs/native-objc-interop.html#extensions-and-category-members">not converted</a> into Swift extensions in most cases</li><li>sometimes Kotlin internal classes are converted into Swift internal classes, and sometimes not</li><li>no support for generic protocol, generic func. This is quite an important point when working with Kotlin Flow.</li><li>no support for default arguments in Swift</li><li>no support of sealed class in Swift</li></ul><p>Some of these nuances can be fixed with the <a href="https://github.com/icerockdev/moko-kswift">gradle plugin</a>, which will generate a more suitable Swift code. For improved support of coroutines and Flow in Swift, you can use this <a href="https://github.com/rickclephas/KMP-NativeCoroutines">library</a>.</p><p>You can find a list of interop nuances in <a href="https://kotlinlang.org/docs/native-objc-interop.html">an article from JetBrains</a>. There is also a <a href="https://github.com/hhru/kotlin-swift-interopedia">repository</a> with a detailed description and explanation of all the nuances of interop and usecases.</p><p>What causes problems:</p><ul><li>Take caution when upgrading the Kotlin version and test the entire app. We had dependency conflicts that caused crashes in iOS and Android runtime.</li><li>Mind the nuances of working with memory in a multi-threaded environment in Kotlin Native. Objects should be immutable when transferred between threads. This problem occurs almost immediately when you try to display data from the server on the screen (although you don’t mutate it) when using the ktor + kotlinx.serialization bundle. There is an <a href="https://github.com/Kotlin/kotlinx.serialization/issues/1450">issue</a> on Github with a hack to work around this problem.</li></ul><p>Now, with the release <a href="https://blog.jetbrains.com/kotlin/2021/08/try-the-new-kotlin-native-memory-manager-development-preview/">of the new memory model</a>, the immutability problems are fading away. It is enabled <a href="https://kotlinlang.org/docs/whatsnew1720.html#the-new-kotlin-native-memory-manager-enabled-by-default">by default</a> since version 1.7.20. Objects can now be accessed from any threads and the tracing garbage collector is used.</p><p>It is important to understand that there can be problems because the technology is not in the release state. The release is <a href="https://youtrack.jetbrains.com/issue/KT-55513">planned</a> for late 2023.</p><h3>Environment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vZxBOxsqNWfz9LzVJUPNNA.jpeg" /></figure><p>We currently use two environments to work with KMM and iOS: Android Studio and Xcode.</p><p>Android Studio alone is not enough for development: it does not allow you to work properly with the iOS code. Syntax highlighting, compiling, and app launching work (you can see how this works under the hood in <a href="https://www.youtube.com/watch?v=2YZnpTLsrQ4">an interview</a> with the KMM plugin developer), but the navigation, hints, and usage search do not. It is generally a pleasure for an iOS developer to use Android Studio: it is convenient to debug and work with Git and the terminal there. But it is quite demanding on resources.</p><p>Due to the limitations of the Android Studio, a developer needs to keep two IDEs open: Android Studio and Xcode. And this increases the developer’s hardware level requirements. At the same time, the Gradle build system consumes a lot of memory. But with 16Gb of RAM you can comfortably use 2 IDEs at once: Xcode and Android Studio in small projects.</p><p><strong>Screenshots of two systems used on different machines:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*le86fyneWaWNwlsXvFJ1PQ.png" /><figcaption>16 Gb</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTc-nch5TM-uGhSwwRiAoA.png" /><figcaption>32Gb</figcaption></figure><p>To solve this issue, we tried AppCode instead of two IDEs. Everything’s out of the box there, and it’s easy to understand if you’ve dealt with Android Studio before. On the other hand, this solution is paid and, unfortunately, JetBrains recently <a href="https://blog.jetbrains.com/appcode/2022/12/appcode-2022-3-release-and-end-of-sales-and-support/">announced</a> that they discontinue developing it.</p><p>For today, we see the parallel use of Xcode and Android Studio as an optimal solution, if the resources of your machine allow it.</p><p>To make sure that all necessary software is available on the developer’s machine, use <a href="https://github.com/Kotlin/kdoctor">KDoctor</a>.</p><p>We have encountered problems assembling the KMM part on Mac systems with Apple Silicon. The solutions from this <a href="https://betterprogramming.pub/some-errors-ive-found-developing-with-kmm-d7480161f15d">article</a> helped us solve the issue. Initially we worked with Rosetta, which increased the build time, but since Kotlin 1.5.30 Apple Silicon chips are supported.</p><h3>Nuances with the use of KMM</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMzQbkFVdL2XGVAxkQeoxg.jpeg" /></figure><h4>Linking common code to an iOS project</h4><p>When you work with KMM in iOS you immediately face a question: how to connect a module with a common code to a project?</p><p>Currently there are two ways to do it:</p><ul><li>Cocoapods</li><li>Regular framework</li></ul><p>When using the regular framework in an iOS project, a script call is added before the build:</p><pre>cd &quot;$SRCROOT/..&quot;<br>./gradlew :shared:embedAndSignAppleFrameworkForXcode</pre><p>Later, <a href="https://kotlinlang.org/docs/native-cocoapods.html#add-and-configure-kotlin-cocoapods-gradle-plugin">the integration with CocoaPods</a> came out and we started using it (we use this dependency manager on iOS). That helped us to get rid of unnecessary steps.</p><p>Under the hood, the plugin automatically generates a podspec file for the shared library.</p><p>A script phase is added inside the podspec. It allows you to build a shared module every time you build an iOS app and see all changes.</p><p><strong>shared.podspec</strong></p><pre>spec.script_phases = [<br>   {<br>       :name =&gt; &#39;Build shared&#39;,<br>       :execution_position =&gt; :before_compile,<br>       :shell_path =&gt; &#39;/bin/sh&#39;,<br>       :script =&gt; &lt;&lt;-SCRIPT<br>           if [ &quot;YES&quot; = &quot;$COCOAPODS_SKIP_KOTLIN_BUILD&quot; ]; then<br>             echo &quot;Skipping Gradle build task invocation due to COCOAPODS_SKIP_KOTLIN_BUILD environment variable set to \&quot;YES\&quot;&quot;<br>             exit 0<br>           fi<br>           set -ev<br>           REPO_ROOT=&quot;$PODS_TARGET_SRCROOT&quot;<br>           &quot;$REPO_ROOT/../gradlew&quot; -p &quot;$REPO_ROOT&quot; $KOTLIN_PROJECT_PATH:syncFramework \<br>               -Pkotlin.native.cocoapods.platform=$PLATFORM_NAME \<br>               -Pkotlin.native.cocoapods.archs=&quot;$ARCHS&quot; \<br>               -Pkotlin.native.cocoapods.configuration=&quot;$CONFIGURATION&quot;<br>       SCRIPT<br>   }<br>]</pre><p>Let’s note that now you don’t need to configure anything manually to communicate the shared part with the iOS part. When you create a project, everything is already set up and works okay.</p><p><a href="https://blog.jetbrains.com/kotlin/2021/07/multiplatform-gradle-plugin-improved-for-connecting-kmm-modules/">Previously</a>, manual tuning was required. And there were cases where an iOS project would not build because it could not see the new changes in the shared module.</p><h4>Where to store common code?</h4><p>In a project, you can also use a monorepo for cross-platform and native code…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PqJHiXRa7waa73sdXGRgfw.jpeg" /></figure><p>…or distribute the cross-platform part independently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_-1n2_mcRfsEMgRqypCQTA.jpeg" /></figure><p>We use a monorepo which allows different developers (both iOS and Android) to write cross-platform code and immediately integrate changes into the native part without intermediate publication of the artifact.</p><h4>Coroutines, Flow</h4><p>An iOS developer can figure out how to use coroutines in Kotlin fairly quickly. Swift 5.5 added an asynchronous approach with async-await and <a href="https://www.wwdcnotes.com/notes/wwdc21/10134/">structured concurrency</a>. This makes asynchrony in Swift and Kotlin similar. That is, an iOS developer can easily write asynchronous code in the shared part, especially if the project is already set up and the approaches to code writing are defined.</p><p>The nuances arise at the Kotlin–Swift interop stage. The default suspend method call in Kotlin turns into a completionHandler in Swift.</p><p>You also need to put the <a href="https://habr.com/users/Throws">@Throws</a> annotation to the suspend methods to alert Swift of a possible error, because Kotlin has no checked exceptions. Without the annotation, if an error occurs in the suspend method, the app crashes.</p><p>In addition to completionHandler, you can use async-await syntax for suspend methods. This feature is currently experimental and has structured-concurrency <a href="https://youtrack.jetbrains.com/issue/KT-47610">limitations</a>.</p><p>Both completionHandler and async-await do not support coroutines cancellation. <a href="https://github.com/rickclephas/KMP-NativeCoroutines">KMP-NativeCoroutines</a> allows to fix this shortcoming.</p><p>We don’t call suspend methods from Swift in our projects because the interaction with the shared is limited to the MVI-Store interface, where we drop the intents and observe the change of the screen state. Like via a callback. And all the work with asynchrony happens inside MVI, only in the Kotlin part.</p><h4>A brief Implementation of MVI</h4><pre>// ios common<br>class MviComponent {<br>    …<br>    fun onStart() {<br>        binder = bind(mainContext = Dispatchers.Main.immediate) {<br>            store.states bindTo ::acceptState<br>        }<br>    }<br><br>    private fun acceptState(state: StateType) {<br>        mviView.render(state)<br>    }<br>}</pre><pre>// ios native<br>final class FeatureView: MviView {<br>    override func render(model: ClaimDetailsStoreState) {<br>      // sending value в VC    <br>    }<br>}</pre><h4>Native libraries in common</h4><p>Sometimes you need to use the native functionality of the platform and refer to it from the common part.</p><p>In most cases the expect/actual mechanism is enough. In that case, you can use native iOS libraries inside the actual implementation. For example, key-value storage is implemented with SharedPreferences on Android, and with UserDefaults on iOS. In such case, you will have the expect class KeyValueStorage in common:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BWS4hFXGo0U1pYGNGx1Nnw.jpeg" /></figure><p>In addition to the expect/actual mechanism, you can use interfaces, where the implementation is put in the DI within the platform.</p><h4>Example with interfaces</h4><pre>//common<br>interface CookieStorage {<br>    suspend fun getCookiesForUrl(link: String): List&lt;Cookie&gt;<br>    suspend fun clearCookie()<br>}<br><br><br>//iOS common implementation<br>class CookieStorageImpl : CookieStorage {<br><br>    override suspend fun getCookiesForUrl(link: String): List&lt;Cookie&gt; { <br>      NSHTTPCookieStorage.sharedHTTPCookieStorage()<br>      …<br>    }<br>       <br>    override suspend fun clearCookie() {<br>        val cookieStore = NSHTTPCookieStorage.sharedHTTPCookieStorage()<br>        ….<br>    }<br>}<br><br>//iOS common di<br>val authPlatformModule = module {<br>    single&lt;CookieStorage&gt; {<br>        CookieStorageImpl()<br>    }    <br>}</pre><p>By the way, this example can be implemented via the <a href="https://android-developers.googleblog.com/2022/10/announcing-experimental-preview-of-jetpack-multiplatform-libraries.html">DataStore KMM implementation</a> by Google.</p><p>One more example of how to implement the interaction with the platform in the common part is to pass a closure to the KMM part from the native part. Although it looks like a hack (you have to use global variables and methods) and sometimes can be avoided.</p><h4>Example with closure</h4><pre>//iOS common<br><br>internal actual fun provideErrorReporters(): List&lt;ErrorReporter&gt; {<br>    return iOSReportersClosure()<br>}<br><br>internal var iOSReportersClosure: (() -&gt; List&lt;ErrorReporter&gt;) = { <br>  emptyList() <br>}<br><br>class iOSDi {<br>    fun setIosReporters(closure: (() -&gt; List&lt;ErrorReporter&gt;)) {<br>        iOSReportersClosure = closure<br>    }<br>}</pre><pre>// iOS native<br>iOSDi().setIosReporters(closure: {<br>    return [IosErrorReporter()]<br>})</pre><p>We almost always use the approach with an interface and platform implementations.</p><h4>Common libraries in native</h4><p>By default, in the native you can use anything that you write in the common module with public visibility.</p><p>But you will have incomplete access to the code of the libraries which you connected in the common.</p><p>To be able to use the libraries from the common in the native iOS part, you need to add an export:</p><pre>cocoapods {<br>    framework {<br>        export(Deps.Kts.Auth.coreAuth)<br>        export(Deps.KmmColors.core)<br>    }<br>}</pre><p>Before starting to develop on KMM, the Android team in Lonto built up some libraries. We were able to split them into the native and the Kotlin parts, and then reuse the Kotlin part in KMM.</p><h3>Implementing specific areas of the project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MOrud5mz49mHhp3NJEQig.jpeg" /></figure><p>In this part of the article we will check out the main aspects of any project, how you can approach them with KMM, and what libraries do we have out there.</p><p>There is a publicly available list of KMM-compatible libraries from the JetBrains developer: <a href="https://github.com/terrakok/kmm-awesome">https://github.com/terrakok/kmm-awesome</a>. Inside you’ll find a large number of libraries. There is a division by sections, so it is easy to navigate there.</p><h4>DI</h4><p>We use Koin as the DI in the KMM part. It’s the most popular library that supports Kotlin, and we’ve had experience with it on Android, which makes it fairly easy to integrate.</p><p>But we can’t use it as a DI in the native iOS part, so we use Swinject. Inside Swinject, the bundle of VC, MVI Store, and other entities is used. And they are only in the iOS part and are not transferred to the common in any way. The MVI Store itself is created in the Koin modules.</p><p>So we have two different dependency graphs: Swinject and Koin. To get them together, we use a layer. It looks like this.</p><p>In the common iOS part, we add a class for the feature called Feature:</p><pre>//shared/src/iOSMain/kotlin/org/example/di/FeatureDi.kt<br>class FeatureDi : KoinComponent {<br><br><br>    fun featureStore(param: Parameter): FeatureStore = get {<br>       parametersOf(param)<br>    }<br>}</pre><p>In the native iOS part:</p><pre>final class FeatureAssembly: Assembly {<br>    <br>    func assemble(container: Container) {<br>        container.register(FeatureViewController.self) { (resolver) in<br>            let store = FeatureDi.featureStore()<br>            return FeatureViewController(store:  store)<br>        }<br>    }<br>}</pre><p>Thus, the methods from FeatureDi KMM are only called inside the Assembly.</p><p>If you need a dependency in the KMM part that is bound to a scope (analogous to Swinject’s custom scope), the scope is created in Koin.</p><p>If necessary, you can tell from the native part at what point to close the scope:</p><pre>class FeatureDi : KoinComponent {<br>   fun closeFeatureFlow() = getScope&lt;FeatureScope&gt;().close()<br>}</pre><p>This layer allows you to make the two DIs of the framework independent of each other.</p><p>Of course, in a perfect world there should be one framework for DI without any layers. It will support both native and cross-platform dependencies. This is how it works on Android with Koin. But I haven’t seen such implementations for iOS yet. If you know any, please leave a comment. 👇</p><h4>Navigation</h4><p>For this part, there are currently no ready-made solutions for KMM that will support navigation both in iOS and Android.</p><p>What’s available:</p><ul><li><a href="https://github.com/AlexGladkov/Odyssey">Odyssey</a> and <a href="https://github.com/adrielcafe/voyager">Voyager</a> support compose multiplatform navigation, but they do not work with iOS.</li><li><a href="https://github.com/arkivanov/Decompose">Decompose</a> allows you to break down functionality into components with regard to lifecycle and add navigation</li></ul><p>These solutions didn’t work for us, because in our projects we need to support navigation considering different implementations of the platform UI (Fragments/UIKit/Compose/SwiftUI) and, accordingly, we need to support different navigation approaches. At the same time, currently we don’t want to radically change the paradigm for creating functionality, as we would have to do with Decompose.</p><p>That’s why we use native navigation now. In iOS this is done through the Coordinator.</p><p><strong>Who is responsible for the navigation logic?</strong></p><p>In most cases, the navigation is simple: just moving between the screens according to the preset rules. In such cases, we notify from the business logic (Store) that some event has occurred. E.g., a request has been created. In the platform part, if the event comes, we navigate to a given screen. If the request has been created, we return to the screen with the list of all requests.</p><p>But sometimes the logic is more complicated. For example, the flow of screens where the transitions are controlled by the business logic. And you can go from each screen to any other.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uccGI_rLJNfuQRgt-LrHhg.jpeg" /></figure><p>In this case, the rule above will not work: you will have to create a lot of different events and react to everything on each screen within the flow.</p><h4>Possible navigation events</h4><p>Screen1</p><ul><li>navigateToScreen2</li><li>navigateToScreen4</li></ul><p>Screen2</p><ul><li>navigateToScreen3</li><li>navigateToScreen4</li></ul><p>Screen3</p><ul><li>navigateToScreen2</li><li>navigateToScreen4</li></ul><p>Screen4</p><ul><li>navigateToScreen1</li><li>navigateToScreen3</li><li>navigateToScreen5</li></ul><p>In such cases, we create an event NavigateTo(screen). When the platform part accepts this event, it goes to the screen with no additional calculation. And the state machine with transition logic is in the general part.</p><h3>Network</h3><p>When working with the network with libraries, everything is ok.</p><p>We have <a href="https://ktor.io/">Ktor</a> that allows us to send cross-platform queries. You can configure all the necessary functionality in it. Under the hood, a native engine is used to execute queries, such as URLSession.</p><p>If you have GraphQL, there is an <a href="https://www.apollographql.com/docs/kotlin/">Apollo</a> client for pure Kotlin. It works just fine in KMM.</p><p>When working with the network, we had a problem with sending files through Ktor: how to send a file to the server using streams, that is without uploading it completely into the memory.</p><p>In Ktor, you can send form fields using a special class: <a href="https://api.ktor.io/ktor-io/io.ktor.utils.io.core/-input/index.html">Input</a>. It is abstracted from the content. In Android, you can get an InputStream from a file and convert it to Input using an <a href="https://github.com/ktorio/ktor/blob/0081f943b434bdd0afd82424b389629e89a89461/ktor-io/jvm/src/io/ktor/utils/io/streams/Input.kt">extension</a>. This way, when sending a file, bytes from the file InputStream will be read, and the file will not be saved in the memory.</p><p>In iOS, there is no out of the box solution to get Input for a file (the file is obtained from the URL). You have to write the transfer logic yourself.</p><p>You can also use ByteArray to send the file, but then the whole file is put into memory.</p><h4>Example of implementation for ByteArray</h4><pre>let data = Data(contentsOf: url)<br>let byteArray = data.toArray(type: UInt8.self)<br>let kotlinByteArray = KotlinByteArray.init(size: Int32(byteArray.count))<br>let intArray: [Int8] = byteArray.map {<br>    Int8(bitPattern: $0)<br>}<br>for (index, element) in intArray.enumerated() {<br>    kotlinByteArray.set(index: Int32(index), value: element)<br>}</pre><p>We used this option because it suited our task: we could only choose small files.</p><h4>UI</h4><p>KMM has nothing to offer on the UI side yet, but it didn’t aim in this direction anyway. There is a <a href="https://blog.jetbrains.com/ru/kotlin/2021/12/compose-multiplatform-1-0-is-going-live/">compose multiplatform</a> that works steadily on Android and desktop, but in iOS it is only in preview. You can see work examples <a href="https://www.youtube.com/watch?v=Lw2JopLvOuc">here</a>.</p><p>The iOS compose multiplatform is still far away from being stable, so we use native UI: SwiftUI, UIKit.</p><p>But still, in KMM, you can share something in the presentation layer (we use <a href="https://github.com/icerockdev/moko-resources">MOKO-Resources</a> for this):</p><ul><li>strings with translations</li><li>colors</li><li>images, only bitmap by default; you can use <a href="https://github.com/icerockdev/moko-resources/issues/29">workarounds</a>, the <a href="https://github.com/jcraane/kmm-images">kmm-images library</a></li><li>fonts</li></ul><p>Under the hood, the library generates native resources for each platform from KMM at the project compiling stage.</p><p>In addition, we’ve reused the themes of the app between the platforms so that when you change night mode the theme automatically changes. We plan to write an article about this implementation.</p><h3>Debugging an app</h3><p>When debugging an app, the problem of multiple IDEs comes up. You can either debug with Xcode using the <a href="https://github.com/touchlab/xcode-kotlin">xcode-kotlin</a> plugin or with AndroidStudio, AppCode. Our developers use both approaches, depending on personal preference.</p><h3>Crashes</h3><p>When a crash occurs in the KMM part, the error always points to the assembly code. But to figure out the causes of the error it is useful to check out the stack trace of the flow. It helps to find out approximately where the error occurred. You can also go to the KMM file by clicking on a stack trace frame. But the exact location of the error won’t be highlighted.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vK3HRxebGJxxnrboILgLBA.jpeg" /></figure><p>There may also be problems with the display of logs in Crashlytics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4h-P27iQE63Dcp19xK1_EA.jpeg" /></figure><p>You can use <a href="https://github.com/touchlab/CrashKiOS">CrashKit</a> for more detailed information.</p><h3>Logging non-critical errors</h3><p>Non-critical error logging in KMM is almost invariable regarding native development.</p><ol><li>We create an ErrorReporter interface that can log errors to the service:</li></ol><pre>interface ErrorReporter {<br>    fun setUserId(userId: String)<br>    fun logError(throwable: Throwable)<br>}</pre><p>2. We create a composite reporter to be able to send errors to different services:</p><pre>class CompositeErrorReporter(<br>    private val reporterList: List&lt;ErrorReporter&gt;<br>) : ErrorReporter {<br><br>    override fun setUserId(userId: String) {<br>        reporterList.forEach { it.setUserId(userId) }<br>    }<br><br>    override fun logError(throwable: Throwable) {<br>        reporterList.forEach { it.logError(throwable) }<br>    }<br>}</pre><p>3. We provide platform loggers:</p><pre>//Common<br>internal expect fun provideErrorReporters(): List&lt;ErrorReporter&gt;<br><br>  //DI<br>factory&lt;ErrorReporter&gt; {<br>    CompositeErrorReporter(<br>        reporterList = provideErrorReporters()<br>    )<br>}<br><br>//Common iOS<br>internal actual fun provideErrorReporters(): List&lt;ErrorReporter&gt; {<br>    return iosReportersClosure()<br>}<br><br>internal var iosReportersClosure: (() -&gt; List&lt;ErrorReporter&gt;) = { emptyList() }</pre><pre>//Native iOS<br>@objc class CrashlyticsIosErrorReporter: NSObject, ErrorReporter {<br>    func logError(throwable: KotlinThrowable) {<br>      // send throwable to crashlytics<br>    }<br>}<br><br>iOSDi().setIosReporters(closure: {<br>    return [IosErrorReporter()]<br>})</pre><p>The native reporter could potentially be moved to common ios.</p><p>4. In common we create a connection between the logger and the reporter. We use <a href="https://github.com/AAkira/Napier">Napier</a> as our logger.</p><pre>class ErrorReporterAntilog(<br>    // CompositeErrorReporter is substituted as ErrorReporter<br>    private val errorReporter: ErrorReporter <br>) : Antilog() {<br>    override fun performLog(...) {<br>         errorReporter.logError(exception)<br>    }<br>}</pre><pre>//when running app in iOS native<br>Napier.releaseBuild(antilog: ErrorReporterAntilog…)</pre><h3>Memory leaks</h3><p>One of the things you have to deal with when developing an app is making sure that there are no memory leaks. In iOS it is a hard task even without KMM: there are no tools to timely detect memory leaks.</p><p>You should use the <a href="https://developer.apple.com/documentation/xcode/gathering-information-about-memory-use">Memory Graph Debugger</a> to periodically check that nothing has leaked. Or <a href="https://medium.com/bitso-engineering/finding-memory-leaks-in-ios-like-a-pro-83a0212309b6">write tests</a> and run them on CI. Android has a <a href="https://github.com/square/leakcanary">leakcanary</a> library that allows you to check for basic leaks related to the framework. Unfortunately, there is no similar solution for iOS.</p><p>With KMM, we can resort to the same leak-tracking techniques in iOS as in native:</p><ol><li>At some point we realize that something is going wrong 🙈:</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/326/1*wcXxnVm2yJVi_-a6Swi_Ww.jpeg" /></figure><p>2. We open the Memory Graph Debugger:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*unkZnuSM4xgN_izKPHN0Lg.jpeg" /></figure><p>3. We see additional info about the leaking object:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbtCjlpUT-7IWZVY_bQUoQ.png" /></figure><p>As you can see from the figure above, nothing in it indicates where the leak happened. And in our experience, there are always library guts in the leaks. So it can take a long time to find the problem.</p><h3>Process</h3><p>To describe the process, let’s consider a project with four mobile developers: two for Android and two for iOS. The iOS developers had no experience with KMM before.</p><p>At first, the Android team develops the KMM features in the project, and the iOS team plugs them when they are ready, tweaking only the UI part.</p><p>Over time, iOS developers join the code review of the KMM part in observation mode. A few months later, iOS developers are already implementing template features and logic edits within KMM. After another couple of months, iOS developers are fully proficient in KMM development.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3HLDJJ0YVEeovpSw9CyJZA.jpeg" /></figure><p>In November, part of the Android team was on vacation, so iOS developers did most of the KMM tasks.</p><p>When considering the timeline, please note that our team did not have a goal to teach iOS developers to implement KMM as quickly as possible. Given an existing project with approved and established approaches, this can be done even faster.</p><p>We also went through the process of changing the division of feature implementation process into independent parts:</p><ol><li>Initially, there were three objectives for the feature: KMM, Android, and iOS. Firstly, the KMM task was performed, and then the two platform tasks. This approach worked badly for us: at the time of implementing a native task (e.g. for Android) it turned out that we had missed something in KMM and needed to refine the KMM module. But the rework also affected the other platform, which by that time could have been in the process, and we had to rework it.<br>We did not collect statistics on the number of such tasks, but we felt there were about 60–70%. And every developer was spotting this problem on retro.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQXyX8A5UxehsYgj048O4w.jpeg" /></figure><p>2. Now we divide the implementation of the task into two parts: KMM + the first platform, and the second platform. That is, at first we develop the KMM with a platform part, such as Android, if the Android team was the first to come to the implementation of the functionality. After that, the second platform part is developed, e.g. iOS. This is how we reduced the rework in KMM. Although they do happen when the API of one of the platforms is not okay.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pYEJi5KbN6c6SUCHs887MQ.jpeg" /></figure><p>Another thing I would like to point out is that since we use a monorepo, any developer can affect the KMM part in their task. And changes there can break platforms.</p><p>Example. An Android developer changed the KMM, which broke the iOS part. And the developer might not even have seen it, because he never builds an iOS project locally. You can control it by tests, but it is minimally enough to add the “autobuild IOS and Android projects” step in CI before closing the merge request.</p><p>So that the guys who implement KMM understand how it integrates with platforms they don’t understand, we held sessions explaining the basic components and how they relate to Android and iOS. These sessions also helped developers of neighboring platforms to better localize bugs and even to fix not-so-sophisticated bugs when there are changes in KMM.</p><p>In theory, not all Android developers can have a working MacOS machine. In this case, you will need the help of iOS developers to integrate KMM with iOS and edits.</p><h3>Bottom line</h3><h4>Technology Status</h4><ul><li>KMM has its nuances, and we discussed them in the article. But during the development period we did not encounter any blockers that made us think about abandoning KMM and going back to the native or moving to another cross-platform technology.The iOS developers <strong>embraced KMM well</strong>: everyone on our team has a desire to write a cross-platform part. That said, I’m sure it won’t be the case for all developers in general.</li></ul><h4>Personal impression</h4><ul><li>The iOS developers <strong>embraced KMM well</strong>: everyone on our team has a desire to write a cross-platform part. That said, I’m sure it won’t be the case for all developers in general.</li><li>The iOS and Android teams have become <strong>more united</strong>: not only they discuss common development concepts now, but also common implementation.</li></ul><h4>Business</h4><p>In general, the article is not intended to justify KMM to business, but without these conclusions it looks incomplete.</p><ul><li>Savings in development time depends on the project.<br>In our current projects, the ideal time saving is about <strong>25%</strong>. The ratio of time spent on business logic implementation to time spent on UI is 50/50. So, we reduce the implementation of the business logic on one of the platforms. In reality the saving is less: developers need to immerse themselves in the new technology, occasionally there are reworks in the KMM part depending on the platforms, and infrastructure difficulties.<br>It is difficult to estimate <em>exactly</em> how much less: to do this, you need to compare the native vs KMM on the same projects. The time saving will be greater if the projects have a lot of business logic on the mobile client: offline-first solutions.</li><li><strong>Almost 50%</strong> time saving on rework if only the backend/logic is changed without changing the UI.</li><li>The time for iOS developers to immerse themselves in KMM from 0 to implementing complex features is <strong>about 4 months</strong>. And it was not our team’s goal to teach iOS developers how to implement KMM as quickly as possible. Given an existing project with approved and established approaches, this can be done even faster.</li><li><strong>The bus factor increases</strong>: if the iOS team lacks time, is busy on another project, or is on vacation, Android devs can refine KMM logic instead of them.</li><li>We were able to transition to cross-platform <strong>without additional hiring</strong> or <strong>retraining</strong> people.</li><li>Our approach to developing the KMM part is not too different from the native Android approach, which we have been working on for a long time. And it speeds up the immersion of a new teammate into KMM quite a bit: a new Android developer recently joined us, and <strong>in less than a week</strong> he was able to work on the KMM part. Part of that time was spent on diving into the MVI approach.</li></ul><p>We welcome you to share your comments about using KMM in the mobile development team. How do you involve iOS developers in cross-platform development?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c23cded1a50" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/kmm-through-ios-developers-eyes-8c23cded1a50">KMM Through iOS Developer’s Eyes</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Grafana Loki Configuration Nuances]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/grafana-loki-configuration-nuances-2e9b94da4ac1?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/2e9b94da4ac1</guid>
            <category><![CDATA[grafana-loki]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[grafana]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Igor Latkin]]></dc:creator>
            <pubDate>Wed, 31 May 2023 07:55:50 GMT</pubDate>
            <atom:updated>2023-10-31T15:40:42.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EuhWxZNedff03OV7c_6_Ow.jpeg" /></figure><p>Hi! My name is Igor, I am a co-founder and a system architect at <a href="https://www.lonto.io/">Lonto</a>. We deal with different tasks, from corporate systems to custom projects, mobile development, and DevOps. The experience we’ve gained allows us to help our customers cope with the infrastructure and its bottlenecks using a variety of tools.</p><p>This article is based on <a href="https://youtu.be/8ZAIwG2ftrE">my talk</a> at Slurm’s School of Monitoring. In it, I wanted to share best practices for the Grafana Loki set up for collecting logs in infrastructure that we harvested through the years of its usage.</p><p>In my opinion, the threshold to enter Loki is quite low, and there are many tutorials on the Web. So I will talk about the more complex and not quite obvious settings that I have often encountered when working with Grafana Loki.</p><p><strong>This is the article outline:</strong></p><ol><li>The task of collecting logs</li><li>Ways to launch Loki</li><li>The arrangement of Grafana Loki architecture</li><li>Minimum Loki configuration</li><li>Cluster and High Availability solutions configuration</li><li>Timeouts</li><li>Message sizes</li><li>Chunks</li><li>Parallelism</li><li>Optimizing the Write Path</li></ol><h3>The task of collecting logs</h3><p>Four basic questions to ask yourself before trying to integrate any logging system:</p><ol><li>How do I collect logs?</li><li>How do I extract the right metadata from them to make it easier to process logs in the future?</li><li>How do I store this data so that I can record and find it faster (probably the most difficult question)?</li><li>How do I query the logs?</li></ol><p>Every system, be it syslog, Elasticsearch, systems built on ClickHouse, or even Grafana Loki itself, answers these questions differently.</p><p>So when we discuss the architecture, we’ll get back to how Grafana Loki differs from Elasticsearch conceptually, and why it wins in terms of log storage cost.</p><p>The log collection pipeline usually looks simple and straightforward:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ehWMpVRuEjwBFSXlveP34Q.png" /></figure><p>So, we have a variety of data sources we get logs from: Kubernetes clusters, virtual machines, Docker containers, and others. They go through a collect, process, and filter phase.</p><p>Then they are saved in a certain form, depending on the storage you use. For example, as a database if you work with ClickHouse, or as a S3 Bucket in Grafana Loki. But note that every user who retrieves data from the other side may have different action scripts. For example: to retrieve logs for a year or for the last 10 minutes to filter data on them.</p><h3>Ways to launch Loki</h3><p>There are three ways to launch Loki which, by and large, differ in scale.</p><h4>Single-binary</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*tRtANLlc_Ew5sE3501XJcA.png" /></figure><p>This method is the easiest and is mostly used in the primary Loki tutorials. The logic is the following: we take a binary file, run it, and connect it to a Storage.</p><p>The Storage role can be performed by both the file system on which our process is running and the remote S3 Bucket. It doesn’t matter here. This approach has its advantages. For example, the ease of launching: you need only a minimum configuration, which we will check out below. The disadvantage is poor fault tolerance: if the machine crashes, the logs are not written at all.</p><p>The situation can be improved:</p><ul><li>Run the same Loki process with the same config on two different virtual machines</li><li>Combine them into a cluster using the memberlist section</li><li>In front of them, put any proxy, like Nginx or HAProxy</li><li>The main thing is to connect everything to one Storage</li></ul><p>Accordingly, you can scale the process further, i.e. run three, four, or five nodes, etc.</p><p>In the result you will get more or less scheme as the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ruqPh4ynv8D5FJgwapQ9Ug.png" /></figure><p>Note that Loki does both writing and reading. Therefore, the load is evenly distributed across all instances. But in fact it is quite uneven, because sometimes there are a lot of reads, while other times there are a lot of writes.</p><h4>SSD: Simple Scalable Deployment</h4><p>The second method follows the first one and allows to separate the read and write processes. That way, for example, we can run processes that are more disk-dependent on one hardware and less dependent ones on another.</p><p>You need to pass the -target=write or -target=read flag to run, and each of these processes runs the entities that are responsible for the specific query path: write or read. Similarly, you need to put a proxy in front of all instances. It will proxy:</p><ul><li>write queries → to write nodes</li><li>the rest of the queries → to read nodes</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkLi550VyXaRbfwQ6jeXew.png" /></figure><p>Grafana considers this to be the most recommended way to launch and actively develops it.</p><h4>Microservices mode</h4><p>Microservices mode is a more advanced way where we run each Loki component independently.</p><p>There are a lot of components, but they are easily separated from each other, and they can be divided into two or even three groups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2PQxg2HstILIkYCR3cwlCw.png" /></figure><ol><li><strong>The write component group: </strong>Distributors and ingesters that write to the Storage.</li><li><strong>The read component group:</strong> “query-frontend,” “querier,” and “index gateway.” These are the components that deal with execution of queries.</li><li><strong>All other utility components</strong>: e.g. caches, “compactor,” and others.</li></ol><h3>The arrangement of Grafana Loki architecture</h3><p>Let’s dwell a little more on the architecture to understand what is configured in different sections.</p><p>First, let’s check out how the data in the block is indexed. Unlike Elasticsearch, which indexes all documents in full-text and in their entirety by default, Grafana Loki goes the other way: it indexes not the contents of the logs, but their metadata only, i.e. time and labels.</p><p>These labels are very similar to Prometheus labels. I think many of you are familiar with them.</p><p>We end up storing a very small data index in Grafana because there is very little data in it. Here I want to point out that with Elasticsearch the index is often more bloated than the data itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*41EzpBnbw40ZqAzYPdepvg.png" /></figure><p>We keep unindexed data as it is in the order in which it appears. If you want to filter them out, we can use “grep”-like search built-in into Loki.</p><p><strong>Stream</strong> is a unique set of labels, even though the logs may come from the same source.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E_ZYZP6sW81ZRM-uCv5OCw.png" /></figure><p>In this case, the component=”supplier” label generates a new stream. We will need this in the future, since the settings relating to rate-limits and restrictions often apply to the stream.</p><p><strong>Chunk</strong> is a set of several log lines. You take the log lines, put them into one entity, call it a “chunk,” compress it, and put it in the Storage.</p><p>Now let’s go back to the architecture and take a closer look at the write and read paths and their differences.</p><p><strong>Write path.</strong> The logging entry point in Loki is an entity called <em>Distributor</em>. This is a stateless component. Its task is to distribute the query to one or more ingesters.</p><p>Ingesters are stateful components. They compose a so-called <a href="https://en.wikipedia.org/wiki/Consistent_hashing">hash ring</a>, a system of consistent hashing. It makes it easier to add and remove the ingesters from the cluster. All ingesters are connected to the same Storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*ppx8u7hCOXNOzZAwujOSXQ.png" /></figure><p><strong>Read path</strong> is more complicated, but the principle is similar. There are stateless components: <em>query-frontend</em> and <em>querier</em>. Query-frontend is a component that helps to split the query, so that it can be executed faster.</p><p>For example, let’s imagine that you need to query data for a month period. Using the query frontend, we divide the query into smaller intervals and send it in parallel to several queriers. After that we merge the result and return it to client.</p><p><strong>Querier</strong> is a component that queries logs from the Storage. If we get new data from the ingesters that has not yet been written to the Storage, the querier asks for it too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*UVyL29FK0FCJU0QnpSraNA.png" /></figure><h3>Minimum Loki configuration</h3><h4>Filesystem</h4><p>This configuration focuses on working with the file system when Loki is running in a single instance mode. I will tell you about the most important configuration sections.</p><p><strong>Loki</strong> is a tool that is constantly evolving to simplify and improve the way you work with configuration. One of the best changes was introduced a couple of versions ago: the “common” section. When there are several repeating items in a configuration, the “common” combines them in different parts of the config. That is, if before you had to configure the ring, storage, and other elements for the ingester, querier, and distributor separately, now you can do it all in one place.</p><pre>auth_enabled: false<br><br><br>server:<br>  http_listen_port: 3100<br><br><br>common:<br>  path_prefix: /tmp/loki<br>  storage:<br>    filesystem:<br>      chunks_directory: /tmp/loki/chunks<br>      rules_directory: /tmp/loki/rules<br>  <br>  replication_factor: 1<br><br><br>  ring:<br>    instance_addr: 127.0.0.1<br>    kvstore:<br>      store: inmemory<br><br><br>schema_config:<br>  configs:<br>    - from: 2020-09-07<br>      store: boltdb-shipper<br>      object_store: filesystem<br>      schema: v12<br>      index:<br>        prefix: loki_index_<br>        period: 24h</pre><p>Here you can see that storage is set up as a file system, and it shows where the chunks are stored. There you can also specify where to store the index, alerting rules, etc.</p><p><strong>schema_config</strong> is a config to specify how the data is stored: as chunks &amp; indexes. Nothing has changed here in general since long ago, but sometimes new scheme versions appear. Therefore, I recommend reading the change logs periodically so that you could update your Loki schemes in time and use the latest improvements.</p><p>Once several instances appear, you need to combine them in a cluster that runs on the “memberlist” protocol (you can also use third-party systems such as etcd or consul). That is a <a href="https://en.wikipedia.org/wiki/Gossip_protocol">Gossip</a> protocol. It automatically finds Loki nodes according to a certain principle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QCYlr7pyOH3anTlQ8khT4w.png" /></figure><pre>auth_enabled: false<br><br><br>server:<br>  http_listen_port: 3100<br><br><br>common:<br>  path_prefix: /tmp/loki<br>  storage:<br>    filesystem:<br>      chunks_directory: /tmp/loki/chunks<br>      rules_directory: /tmp/loki/rules<br>  <br>  replication_factor: 1<br><br><br>  ring:<br>    kvstore:<br>      store: memberlist<br><br><br>schema_config:<br>  configs:<br>    - from: 2020-09-07<br>      store: boltdb-shipper<br>      object_store: filesystem<br>      schema: v12<br>      index:<br>        prefix: loki_index_<br>        period: 24h<br><br><br>memberlist:<br>  join_members:<br>    - loki:7946</pre><p>There are many different ways to automatically configure a cluster, and they work just fine. For example, you can specify different settings in the memberlist.join_members section:</p><ul><li>Single host address</li><li>List of addresses</li><li>dns+loki.local:7946 — Loki will make an A/AAAA DNS query to get a list of hosts</li><li>dnssrv+_loki._tcp.loki.local — Loki will make a SRV DNS query to get not only the hosts but also the ports list</li><li>dnssrvnoa+_loki._tcp.loki.local — SRV DNS, a query without A/AAAA query</li></ul><p><strong>Why do you need it?</strong> There are components within Loki that need to know about each other. For example, distributors need to know about ingesters. Therefore, they are registered in the same ring. After that, distributors know which ingesters to send a record request to. Another example is compactors which must work in a single instance in a cluster.</p><h4>S3 as a storage</h4><p>S3 is the most recommended way to store logs in Loki, especially if you deploy Loki into Kubernetes cluster. When we use S3 as storage, the configuration changes slightly:</p><pre>auth_enabled: false<br><br><br>server:<br>  http_listen_port: 3100<br><br><br>common:<br>  path_prefix: /tmp/loki<br>  storage:<br>    <br>    s3: # The &quot;filesystem&quot; section changes to s3<br>      <br>      s3: https://storage.yandexcloud.net<br>      bucketnames: loki-logs<br>      region: ru-central1<br>      access_key_id:<br>      secret_access_key:<br>  <br>  replication_factor: 1<br><br><br>  ring:<br>    kvstore:<br>      store: memberlist<br><br><br>schema_config:<br>  configs:<br>    - from: 2020-09-07<br>      store: boltdb-shipper<br>      object_store: filesystem<br>      schema: v12<br>      index:<br>        prefix: loki_index_<br>        period: 24h<br><br><br>memberlist:<br>  join_members:<br>    - loki:7946</pre><p>Tips:</p><ul><li>Use https:// instead of s3://. That way you guarantee the use of an encrypted connection</li><li>You can specify several bucketnames to distribute storage</li><li>You can use ACCESS_KEY_ID and SECRET_ACCESS_KEY environment variables to configure S3 access keys</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*DN_0ts9JK_7ISwtwhNvRuA.png" /></figure><p>We change storage to S3, specify the endpoint, bucketnames, and other configurations that apply to S3.</p><p>Note that bucketnames are plural, meaning that you can specify several of them at once. This way Loki will begin to distribute the chunks evenly over all the specified buckets to reduce the load on a single bucket. For example, you need this when your hoster has RPS restrictions per bucket.</p><h3>Cluster and High Availability solutions configuration</h3><p>Suppose we’ve recorded logs in several nodes. One of them failed and you can’t query data from it, because it did not have time to write them into the storage.</p><p>High Availability in Loki is provided through the use of replication_factor option. With this setting, the distributor sends the logging query to more than one ingester replica.</p><pre>auth_enabled: false<br><br><br>server:<br>  http_listen_port: 3100<br><br><br>common:<br>  path_prefix: /tmp/loki<br>  storage:<br>    s3:<br>      s3: https://storage.yandexcloud.net<br>      bucketnames: loki-logs<br>      region: ru-central1<br>      access_key_id:<br>      secret_access_key:<br>  <br>  replication_factor: 3  # Take a note of this field<br><br><br>  ring:<br>    kvstore:<br>      store: memberlist<br><br><br>schema_config:<br>  configs:<br>    - from: 2020-09-07<br>      store: boltdb-shipper<br>      object_store: filesystem<br>      schema: v12<br>      index:<br>        prefix: loki_index_<br>        period: 24h<br><br><br>memberlist:<br>  join_members:<br>    - loki:7946</pre><p><strong>replication_factor:</strong></p><ul><li>The distributor sends chunks to multiple Ingesters</li><li>Minimum of 3 for 3 nodes</li><li>Allows 1 of 3 nodes to fail</li><li>maxFailure = (replication_factor / 2) + 1</li></ul><p>The distributor sends the chunks to several ingesters at once.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dgXLjeFr8-WWsmsfcnKC5g.png" /></figure><p>For data deduplication in the boltdb-shipper several caches are being <a href="https://grafana.com/docs/loki/latest/operations/storage/boltdb-shipper/#write-deduplication-disabled">used</a> — chunk_cache_config config section for chunks and write_dedupe_cache_config for indexes. Moreover, queriers act in the whole deduplication process by filtering duplicated log lines (based on timstamp and the contents). More on this <a href="https://grafana.com/docs/loki/next/get-started/architecture/#read-path">here</a> and <a href="https://github.com/grafana/grafana/issues/26714#issuecomment-704792604">here</a>.</p><h3>Timeouts</h3><p>Quite a hard topic, because when you set up Loki incorrectly, you can often see errors like 502, 504.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EWfxAWoN2U8OaoY979txXQ.png" /></figure><p>To better understand the errors, you should firstly increase the timeouts to sufficient values in your project. The second thing to do is to properly configure several types of timeouts.</p><ol><li>The http_server_{write,read}_timeout configures a base timeout for the web server response time.</li><li>The querier.query_timeout and querier.engine.timeout sets the maximum running time of the engine that directly executes read queries.</li></ol><pre>server:<br>  http_listen_port: 3100<br>  http_server_write_timeout: 310s<br>  http_server_read_timeout: 310s<br><br><br>querier:<br>  query_timeout: 300s<br>  engine:<br>    timeout: 300s</pre><p>If you use a proxy like NGINX in front of Loki, you should increase the timeouts there as well (proxy_read_timeout and proxy_send_timeout).</p><pre>server {<br>  proxy_read_timeout = 310s;<br>  proxy_send_timeout = 310s;<br>}</pre><p>You should also increase the timeout on the Grafana side. You can do this in the [dataproxy] section of the config.</p><pre>[dataproxy]<br>timeout = 310</pre><p>The best approach is to set the minimum of all four types of timeouts at the querier (300s in the example). That way it will finish first, and all the next ones, for example HTTP servers, Nginx, or Grafana, will take a bit longer.</p><p>The default timeout is very small, so I recommend increasing these values.</p><h3>Message sizes</h3><p>The topic may seem complicated because the origin of some errors is not obvious.</p><p><strong>Message sizes,</strong> grpc_server_max_{recv,send}_msg_size are the limits of the possible size of the logs. The default limits are very small. For example, if there is a large stack trace and 20 MB of logs are sent in one log line, there is no way it can fit into that limit. So it has to be increased.</p><pre>server:<br>  http_listen_port: 3100<br>  grpc_server_max_recv_msg_size: 104857600  # 100 Mb<br>  grpc_server_max_send_msg_size: 104857600  # 100 Mb<br><br><br>ingester_client:<br>  grpc_client_config:<br>    max_recv_msg_size: 104857600  # 100 Mb<br>    max_send_msg_size: 104857600  # 100 Mb</pre><ul><li>The default is 4 MB</li><li>Directly affects the size of logs processed by Loki</li></ul><p>We can’t avoid the encoding of chunks either. The default value is gzip, which is the maximum compression. Grafana recommends switching to snappy, and I agree with them based on my experience. Then the logs may take a little more space in the storage, but reading and writing data becomes more efficient.</p><pre>ingester:<br>  chunk_encoding: snappy</pre><p>The default encoding is gzip:</p><ul><li>Better compression</li><li>Slower queries</li></ul><p>We recommend to use snappy encoding:</p><ul><li>Compression is a little worse</li><li>However, very fast encoding/decoding</li></ul><h3>Chunks</h3><p>There are many chunk settings regarding their size and lifetimes. I recommend not to edit them too much. And you have to really understand what you are doing when you change these values.</p><pre>ingester:<br>  chunk_idle_period: 2h<br>  chunk_target_size: 1536000<br>  max_chunk_age: 2h</pre><p>The defaults are pretty good:</p><ul><li>I don’t recommend changing chunk_block_size and chunk_retain_period at all</li><li>The chunk_target_size can be increased if the chunks are mostly full. This will give them more space</li><li>chunk_idle_period means how long the chunk will live in the ingester’s memory if there are no records in it at all. So, if your streams are mostly slow and half-empty, it’s better to increase the period. The default is 30 minutes</li></ul><h3>Parallelism</h3><p>Another important issue is concurrency.</p><pre>querier:<br>  max_concurrent: 8<br><br><br>limits_config:<br>  max_query_parallelism: 24<br>  split_queries_by_interval: 15m<br><br><br>frontend_worker:<br>  match_max_concurrent: true</pre><ul><li><strong>querier.max_concurrent</strong> shows how many queries one querier can handle in parallel. It is recommended to put about twice the number of CPUs. The default is 10 (be careful with these numbers)</li><li><strong>limits_config.max_query_parallelism</strong> shows the maximum parallelism the tenant has. The <strong>querier.max_concurrent</strong> values must match with <strong>max_query_parallelism</strong> by the formula:<br>[queriers count] * [max_concurrent] &gt;= [max_query_parallelism]</li></ul><p>In our example at least 3 queriers should be running to provide the parallelism value of 24.</p><h3>Optimizing the Write Path</h3><p>There are several write-related settings here: ingestion_write_mb, ingestion_burst_size_mb.</p><pre>limits_config:<br>  ingestion_rate_mb: 20<br>  ingestion_burst_size_mb: 30</pre><p>The defaults are low, so I recommend increasing them. This will allow you to write much bigger logs and do it more often. The other values relate to the tenant, so you have to be careful with them.</p><p>There is a separate setting for streams: per_stream_rate_limit.</p><pre>limits_config:<br>  per_stream_rate_limit: &quot;3MB&quot;<br>  per_stream_rate_limit_burst: &quot;10MB&quot;</pre><p>These are more or less normal defaults in the example. But if they’re starting to constrain you, I recommend breaking up one stream into several by adding a label. This will reduce the stream’s rate-limit obviously. If this is not possible, you can try to increase the limits of course.</p><h3>Summing up</h3><p>In this article I tried to give a detailed explanation of how to work with Loki in the context of configuration:</p><ul><li>The task of collecting logs</li><li>Loki architecture</li><li>3 types of Loki launch strategies</li><li>High Availability in Loki with replication_factor</li><li>Configuration of timeouts and message sizes</li><li>Parallelism — watch these settings very carefully!</li><li>Optimising the write path is generally not a difficult process. You just need to look at the indicators in your monitoring and optimise accordingly</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e9b94da4ac1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/grafana-loki-configuration-nuances-2e9b94da4ac1">Grafana Loki Configuration Nuances</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Manage Infrastructure in GitOps Using Crossplane]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/how-to-manage-infrastructure-in-gitops-using-crossplane-1cc8ca1cfcc3?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/1cc8ca1cfcc3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[gitops]]></category>
            <dc:creator><![CDATA[sermalenk]]></dc:creator>
            <pubDate>Fri, 26 May 2023 12:14:32 GMT</pubDate>
            <atom:updated>2023-05-26T12:16:56.211Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3O7eL20x3gnzohDT_s-FNg.jpeg" /></figure><p>Hi, my name is Sergey, I am the head of the DevOps unit at <a href="https://www.lonto.io/">Lonto</a>.</p><p>We periodically partner with interesting guys and organize events together. The examples of such events are meetings of entrepreneurs, online flat parties, and product management days. This series of three articles is a text version of the speeches from the CTO Day event. The report has two speakers:</p><ul><li>Sergei Malenko, Head of DevOps unit at Lonto</li><li>Sergey Bondarev, Architect at Southbridge</li></ul><p>The report was devoted to the history of app deployment, the main models used for it, and their comparison. We discuss the pull model in detail and show how to use “advanced” tools to manage the infrastructure of large projects and allow developers to independently order elements in the infrastructure for the needs of their apps.</p><p>All in all, we have prepared three articles based on the report. They will follow this order:</p><p><a href="https://medium.com/kts-digital-services-integrator/the-history-of-devops-from-the-beginning-of-time-to-argocd-and-iac-b9f97e0a9f72"><strong>The history and how things evolved</strong></a><em><br>To understand the context, we will check out how the approach to iterative app deployment changed over time.</em></p><p><a href="https://medium.com/lonto-digital-services-integrator/gitops-platform-powered-by-argo-cd-121cfcf85290"><strong>What is ArgoCD and why do we need it, with use cases </strong></a><em><br>We’ll talk about a relatively new turn in the app deployment methods and see what questions can be solved with this tool.</em></p><p><strong>How to manage infrastructure in GitOps using Crossplane ← </strong>you are here 🚩<strong><br></strong><em>A new approach to IaC and how it can be combined with Argo CD</em></p><p>This is the final part of our report, from which you will learn:</p><ul><li>What tools the DevOps used: from manual changes to full automation</li><li>What tools allow you to apply the pull model to manage infrastructure, create virtual machines (VM), and order new servers in data centers</li><li>Two cases in which we combine the ApplicationSet and Crossplane manifests</li></ul><p>Contents</p><ul><li>Manual operation scheme</li><li>The first scripts to start with</li><li>Ansible script</li><li>Ansible automation</li><li>Terraform</li><li>Full automation</li><li>ArgoCD API and push model</li><li>Crossplane</li><li>How to work with Crossplane</li><li>Infrastructure</li><li>Terrajet</li><li>How we created a Crossplane provider with Terrajet</li><li>First case: Bootstrapping of environments</li><li>Second case: Dynamic environments</li><li>Why it’s useful to combine Crossplane and ArgoCD</li><li>Summing up. Why it’s good to automate</li></ul><h3>Manual operation scheme</h3><p>Initially, DevOps engineers did everything manually. They were logging into the system through the web interface on the hosting panel, making a new VM, and logging into it. Or they were ordering a server. They were doing the apt install nginx and setting the server. Everything worked like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qQyepMKGRo9kYLrhuSTsnA.jpeg" /></figure><h3>The first scripts to start with</h3><p>Later, automation arrived. The commands are written in a Bash script and put in the repository. After that, devs go to the server, manually do a “git pull,” get the script, and install the needed services and apps on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hXmCSTVY-8pUm6PTjZk5tg.jpeg" /></figure><p>Many organizations have stopped at this step. To get the VM, you often have to wait for about a week and a half: you have to write a memo, send it, and only then get access.</p><h3>Ansible script</h3><p>The more advanced DevOps replace the SH script with the Ansible script. They put everything in a repository, download it to the server manually, and run Ansible to configure it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3MrNiRxq2GBEpBvrO5UvTw.jpeg" /></figure><h3>Ansible automation</h3><p>The most advanced DevOps automate the launch of the Ansible script. To do this, they put it in the CI/CD. A new server appears, which is brought into the “inventory.” After that, the CI/CD Job is launched. It sets everything up automatically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DoDh1tvDIOa8sqY3g2uFKw.jpeg" /></figure><p>The only inconvenience is that you have to create the server manually.There are solutions that automate all of these processes. For example, with Ansible, you can get VMs through the hoster API. But the most popular tool for automation is Terraform.</p><h3>Terraform</h3><p>A program for managing external resources.</p><p>You do not need to create anything manually for it to work. Just describe the configuration for the future infrastructure, and Terraform will do everything itself:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mA2sHwqFzeZ2Af1ZOUJuFQ.png" /></figure><p>Sometimes Terraform does its job well, sometimes there are problems. The tool is so popular that it has become the de facto standard in the Infrastructure as a Code (IaC) approach.</p><h3>Full automation</h3><p>To get the full automation, Terraform itself needs to be automated. To do this, we put it into the CI/CD, it runs and saves its “state” in the desired system, such as GitLab:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BV0uHM-rfztYy1GXqLSMgw.png" /></figure><h3>ArgoCD API and push model</h3><p>Let’s go back to the dynamic environments from <a href="https://habr.com/ru/company/kts/blog/723760/">part two</a>.</p><p>In the case of using the ArgoCD API and the classic push model, we can insert a separate Job named “build environment,” in which we call Terraform:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4m2HdB2ThZEz2kgLFa0PA.png" /></figure><p>What’s the alternative of the pull model?</p><h3>Crossplane</h3><p>This is another of the IaC tools. Its purpose is the same as Terraform’s: to create infrastructure in the clouds, to deploy databases and clusters. Like ArgoCD, it lives in Kubernetes.</p><p>Unlike Terraform, Crossplane constantly synchronizes the state. Terraform is a console utility: synchronization and changes only happen when we write <strong>terraform plan/apply</strong>. On the other hand, Crossplane uses an agent-based model: it <em>always</em> tracks what is actually in the clouds and what the coder has asked to deploy through configurations. If there are mismatches, Crossplane will try to apply the changes.</p><p>It is a part of the <a href="https://habr.com/ru/company/itglobalcom/blog/459954/">CNCF</a>, a foundation which develops and promotes cloud technology.</p><ul><li>laC tool with tasks similar to Terraform’s</li><li>Lives in Kubernetes</li><li>Manages the infrastructure</li><li>Constantly synchronizes the state</li><li>Is a part of the CNCF</li></ul><h3>Infrastructure</h3><p>The whole infrastructure can be represented as custom resources in Kubernetes: we can describe a Postgres cluster or a Kubernetes cluster through a YAML file, just like we rolled applications in ArgoCD. Eventually this will go to Crossplane. It will take the spec, go to the cloud, and create a Managed Postgres or a Kubernetes cluster. Crossplane can create any infrastructure stuff that a cloud provider has:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Wv4oriri1pmKZzDrmQyLw.jpeg" /></figure><p>Crossplane is supported by:</p><ul><li>AWS</li><li>Google Cloud</li><li>Azure</li><li>Yandex.Cloud</li><li>Digital Ocean</li><li>This list is constantly growing</li></ul><h4>How to work with Crossplane</h4><p>For example, we create a manifest that describes a MySQL cluster. We specify parameters and send it to Kubernetes. Crossplane takes this spec and follows it to get to the Yandex.Cloud API, for example. The base unfolds:</p><pre>apiVersion: mdb.yandex-cloud.jet.crossplane.io/v1alpha1<br>kind: MySQLCluster<br>metadata:<br> name: mysql-auth<br>spec:<br> forProvider:<br>   environment: PRODUCTION<br>   host:<br>     - zone: ru-central1-b<br>   name: mysql-auth<br>   resources:<br>     - diskSize: 10<br>       diskTypeId: network-hdd<br>       resourcePresetId: b2.nano<br>   networkIdRef:<br>     name: default<br>   folderIdRef:<br>     name: default<br>   version: &quot;8.0&quot;</pre><p>Above we see a simple manifest for Crossplane that creates a MySQL cluster in Yandex.Cloud.</p><p>What opportunities do we get? We can describe the entire infrastructure in Helm charts! Not just items within Kubernetes, but any cloud objects for environment setup. For example, DNS records, security groups, networks, and so on.</p><p>Let’s say we want to create a Kubernetes cluster in Yandex.Cloud. We need security-group, cluster description, and node-group. To do this, we create a separate chart in which we describe all these entities. We use “values” to parameterize node groups, the configuration of the cluster itself, the security-group:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KnYKW6twF4du0_97i1-qyw.png" /></figure><p>Next we describe the PostgreSQL cluster. To save resources, it is more convenient to create different databases within the same cluster. To do this, we create two charts:</p><ul><li>The first chart, in which we create the database cluster itself</li><li>The second chart: a specific database and the user to it are created within the cluster.<strong>It is this chart that we can use as a dependency for the charts of the apps themselves.</strong></li></ul><p>This way, a team can ask for a base in a cluster, a DNS record, or any other cloud entity itself through their app chart. They will use dependencies in the form of infrastructure charts.</p><p>For example, let’s consider a backend app deployment. For it, we usually need a database and a user. Developers connect a dependency in the form of the second chart described above to their app’s chart. As a result, ArgoCD deploys both the app itself and the manifests for Crossplane. Crossplane uses these manifests to create a user and a base inside the cluster. Then it creates a secret with connection data. This secret is already pre-mounted to the app pods through the deployment. In the end, everything works automatically:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dod2mN_otx-wMPYPCNE5yA.jpeg" /></figure><h3>Terrajet</h3><p>Terrafom is such a popular tool that you can even order a pizza with it, because it knows how to pull any API. That’s why Crossplane developers created the Terrajet tool. It can generate a Terraform-based provider for Crossplane. Terrajet is useful if your provider still does not support Crossplane.</p><p>Terrajet is mapped to the Terraform provider, and it generates the provider’s code. We end up with a project with a Go code and a build in GitHub Actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FVdvbS_5SfEVg3GQyINKag.jpeg" /></figure><p>How we created a Crossplane provider with Terrajet</p><p>We noticed that our friends at Selectel company did not have a Crossplane provider, so <a href="https://github.com/ktsstudio/provider-jet-selectel">we generated one with Terrajet</a>.</p><p>We tried to create a cluster spec in Kubernetes, but it didn’t work. To do this, you need to change the response status when creating in the Selectel API. This is due to the peculiarities of the Terrajet. When the Selectel API changes status, we can move on.</p><p>Still, we were able to import the current entities. To do this, we specified the cluster ID in the external name. The status and additional parameters appeared. Now we can change the cluster as we want.</p><pre>apiVersion: mks.selectel.jet.crossplane.io/v1alpha1<br>kind: ClusterV1<br>metadata:<br>  name: devopsdemo<br>  annotations:<br>    crossplane.io/external-name: &quot;a58b105d-***-f8d63d83fd85&quot;<br>spec:<br>  forProvider:<br>    zonal: true<br>    projectId: eccc*****f32f<br>    region: ru-2<br>    kubeVersion: 1.22.9<br>  providerConfigRef:<br>    name: default</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9lZJZRrd03WDIpCg9xjLDg.png" /><figcaption><a href="https://github.com/ktsstudio/provider-jet-selectel"><strong>https://github.com/ktsstudio/provider-jet-selectel</strong></a></figcaption></figure><pre>status:<br>  atProvider:<br>    id: a58b105d-***-f8d63d83fd85<br>    kubeApiIp: 45.***.***.***<br>    maintenanceWindowEnd: &quot;03:00:00&quot;<br>    status: ACTIVE</pre><h3>First case: Bootstrapping of environments</h3><p>Now let’s talk about cases where we combine ApplicationSet and Crossplane manifests.</p><p>The DevOps engineer creates a values.yaml file describing the desired environment. ApplicationSet is mapped to the environment folder, so it creates an “application” after the push to the Git, deploying all entities inside Kubernetes (including manifests for Crossplane). It takes these manifests and creates the needed cloud objects for the environment:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_KhBlfrrIN3KvlIn3kbyaQ.png" /></figure><h3>Second case: Dynamic environments</h3><p>In dynamic environments, we can use that second chart to create a separate database and a user within a shared cluster.</p><p>For example, when a developer sends a branch to GitLab, a new database is automatically created in the cluster, and connection settings are thrown into the app secret:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lSYXYMCsEwRMCdzEa-vUyg.png" /></figure><h3>Why it’s useful to combine Crossplane and ArgoCD</h3><p><strong>The team itself creates the infrastructure for the projects.</strong> You can write your own providers for Crossplane. This is useful when you have a large company and a platform team. Platform coders can write their own providers, which, for example, set up VMs inside their infrastructure and apply the needed packages to them.</p><p><strong>The Kubernetes cluster is a single point of interaction with the infrastructure.</strong> Everything related to the infrastructure is represented in the Kubernetes cluster. You don’t need a myriad of repositories: say, for Ansible, for Terraform, and for something else. Coders don’t need to understand the HCL language and create separate merge requests in repositories with the infrastructure.</p><p>Everyone uses Kubernetes resources. Not for deployments, services, and ingresses only. Almost everything is already provided by custom resources: you can use them to manage everything in the platform.</p><h3>Summing up. Why it’s good to automate</h3><p>We started out with a developer who uploads the website to the server via FTP:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1ho8h4b0_lND5UAq3qRNtg.png" /></figure><p>But in this simple scheme, everything is done manually and resides in the mind of a single developer. If there is no developer, the whole thing will collapse.</p><p>That’s why the whole world is trying to automate infrastructure management and app deployment as much as possible. As a result, on the one hand, we come to such complex systems. But on the other hand, these systems allow:</p><ul><li>A large number of teams to work on a project</li><li>To constantly monitor the infrastructure and synchronize its state</li><li>To simplify the delivery of updates to a large number of environments</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJuZuQ66z1ByMUJvo3Julw.png" /></figure><h4>Track articles:</h4><p>Part 1: <a href="https://medium.com/kts-digital-services-integrator/the-history-of-devops-from-the-beginning-of-time-to-argocd-and-iac-b9f97e0a9f72">The History of DevOps: From the Beginning of Time to ArgoCD and IaC</a></p><p>Part 2: <a href="https://medium.com/lonto-digital-services-integrator/gitops-platform-powered-by-argo-cd-121cfcf85290">How the Argo CD Works and How the GitOps Approach Works</a></p><p>In this part, we talked about how infrastructure is managed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1cc8ca1cfcc3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/how-to-manage-infrastructure-in-gitops-using-crossplane-1cc8ca1cfcc3">How to Manage Infrastructure in GitOps Using Crossplane</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[GitOps Platform Powered by Argo CD]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/gitops-platform-powered-by-argo-cd-121cfcf85290?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/121cfcf85290</guid>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[gitops]]></category>
            <category><![CDATA[system-administration]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[sermalenk]]></dc:creator>
            <pubDate>Fri, 26 May 2023 10:56:06 GMT</pubDate>
            <atom:updated>2023-05-26T10:56:06.003Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1fS-HWoy-TFowLDyLIfjMA.jpeg" /></figure><p>Hi, my name is Sergey, I am the head of the DevOps unit at <a href="https://www.lonto.io/">Lonto</a>.</p><p>We periodically partner with interesting guys and organize events together. The examples of such events are meetings of entrepreneurs, online flat parties, and product management days. This series of three articles is a text version of the speeches from the CTO Day event. The report has two speakers:</p><ul><li>Sergei Malenko, Head of DevOps unit at Lonto</li><li>Sergey Bondarev, Architect at Southbridge</li></ul><p>The report was devoted to the history of app deployment, the main models used for it, and their comparison. We discuss the pull model in detail and show how to use “advanced” tools to manage the infrastructure of large projects and allow developers to independently order elements in the infrastructure for the needs of their apps.</p><p>All in all, we have prepared three articles based on the report. They will follow this order:</p><p><a href="https://medium.com/kts-digital-services-integrator/the-history-of-devops-from-the-beginning-of-time-to-argocd-and-iac-b9f97e0a9f72"><strong>The history and how things evolved</strong></a><em><br>To understand the context, we will check out how the approach to iterative app deployment changed over time.</em></p><p><strong>What is ArgoCD and why do we need it, with use cases ←</strong>you are here 🚩<em><br>We’ll talk about a relatively new turn in the app deployment methods and see what questions can be solved with this tool.</em></p><p><strong>How to manage infrastructure in GitOps using Crossplane <br></strong><em>A new approach to IaC and how it can be combined with Argo CD</em></p><p>GitOps is one of the implementations of the pull model, in which Git is the repository of all configurations. Git is the source of truth, it is the only point through which the changes to the infrastructure are done. All pull-model changes are made by a special agent, which then maintains the set state. That is, if you make changes to the infrastructure manually, the agent will notice a discrepancy with what’s in Git and return everything to the correct state, identical to the source of the truth.</p><p>The Argo CD is one of the most popular GitOps tools. It lives inside Kubernetes and deploys entities there. Argo CD provides a handy RBAC, that is rights and access management. In the interface you can track your actions, manage apps, and forcibly synchronize them. The Argo CD is a part of the CNCF, which gives it a lot of credibility.</p><p>Content:</p><ul><li>Argo CD basics</li><li>Operation scheme</li><li>Interface</li><li>Updating apps</li><li>Pros and cons of Argo CD</li><li>Argo CD API</li><li>ApplicationSet</li><li>Examples of using ApplicationSet</li><li>How does ApplicationSet look like</li><li>The bottom line: pros and cons of the GitOps approach</li></ul><h3>Argo CD basics</h3><p>Argo CD can deploy into a cluster:</p><ul><li>Common manifests</li><li>Kustomize</li><li>Jsonnet</li><li>Helm charts</li></ul><p>These manifests can be taken from the Git or Helm repository. Argo CD deploys manifests to Kubernetes clusters only, but not only to the cluster in which it resides itself. It is able to manage a large number of clusters simultaneously.</p><p>The main entities that this tool operates with are:</p><ul><li>cluster</li><li>repository</li><li>application</li></ul><p>Application is the root entity in the Argo CD. It specifies what and where to deploy. The “application” entity is bound to a single “project” object, which is needed to distinguish access rights. There could be many “projects” inside Argo CD. Let’s say these are folders for demarcation of access rights and a convenient hierarchy of apps.</p><p>How the application manifesto looks like:</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br> name: app<br> namespace: argocd<br>spec:<br> # what<br> source:<br>   path: app<br>   repoURL: https://gitlab.ktsstudio.ru/argocd/app.git<br>   targetRevision: HEAD<br> # where<br> destination:<br>   namespace: app<br>   server: https://kubernetes.default.svc<br> # project<br> project: default</pre><p>Everything Argo CD operates on is stored in the cluster itself: all entities are separate “Custom resources” with their own apiVersion and “kind.”</p><p>The figure above shows an example of an “application” that deploys an app. In “source,” we specify from which repository and which folder to take the chart. In “destination” we specify the cluster and “namespace” into which we will deploy. And in the “project” we define which project our app will belong to.</p><h4>Operation scheme</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kpT05dxJC6Kp4M08YVo4Sg.jpeg" /></figure><p>You can find a description of how the Argo CD works <a href="https://argo-cd.readthedocs.io/en/stable/">on the official website</a>. We’ve got an API here that the user interacts with either through the web interface or through the client. There is a repository service that works with repositories and keeps a cache. And the heart of the solution is the Application Controller, which compares the current state of the infrastructure with what is described in the repositories. If changes occur, the app goes into sync status.</p><h3>Interface</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*Rr1R-7nz5_9AsWw1kvxNuw.gif" /></figure><p>The Argo CD has a user-friendly, visual interface. We see the deployment process and everything that is included into the app. Everything is represented as a graph. For example, it displays the deployments, the replica sets created from them, and finally the pods which have been deployed by the replica sets.</p><h3>Updating apps</h3><p>You can update apps in the Argo CD both manually and automatically.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XL0Q24T5QtIFaE7KCY3lmw.png" /><figcaption>Manually</figcaption></figure><h3>Manually</h3><p>In the first case, the developer pushes the project into Git. An image is assembled. Then it is sent to the registry. Next, you need to manually change the tag of this image in values.yaml in the Git repository with charts. The Argo CD detects this and, depending on where the changes were made, applies them to the right environment. Manual deployment raises security concerns: you have to give the developer access to the repository with the charts where the values files are stored.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tcNJEUUK0O31VI1IeERy4w.png" /><figcaption>Automatically</figcaption></figure><h3>Automatically</h3><p>Naturally, we are more interested in this option. The Argo CD has a separately installed Image Updater component which constantly monitors the Container Registry. As soon as the new version arrives there, it changes the image version in the chart itself and applies the changes to the clusters.</p><p>Still, we are not bound to take the latest version every time. We can also use more complex strategies, such as working with regexes or using semantic versions.</p><h3>Pros and cons of Argo CD</h3><p><strong>Pros:</strong></p><ol><li><strong>Constant synchronization.</strong> If Helm fails and hangs up in our case, Argo CD will constantly try to apply changes to the infrastructure.</li><li><strong>User-friendly interface.</strong> Very visual representation of entities deployed in Kubernetes.</li><li><strong>Viewing the logs.</strong> We open the pod, go to the description, and see the Logs tab. It will display all the events that took place. You can see the logs of all running and failed pods. As long as there are few logs, such as 50 lines, everything works quickly. But if their number increases, it is worth using the web interface of a separate log collection system for viewing.</li></ol><p><strong>Cons:</strong></p><ol><li><strong>Adding apps manually.</strong> For example, we bought a new cluster and want to add something to it. We will have to manually add a new “application” to the repository and specify where to and where from we are adding projects. Because of the difficulty of adding new apps, there is another disadvantage.</li><li><strong>Impossibility to create the environment dynamically.</strong> It is not possible to track the moment when a developer pushes something into a branch. We will still have to go to another repository, create an “application” there, and only then will our app appear. But there are two solutions to this problem.</li></ol><p>In fact, these disadvantages are solved in Argo CD. We will consider this further by comparing two approaches to solving them.</p><h3>Argo CD API and push model</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cZx9I4vzH_gbFKn-94cEzg.png" /></figure><p>If we’ve used Helm, we remove the Helm Upgrade command and do kubectl create app.yaml<strong>, </strong>kubectl upgrade app.yaml<strong> instead.</strong> Accordingly, the Argo CD will start to track all changes. When we make a new dynamic environment, we create these custom resources through the Argo CD API or directly post a YAML with the manifest to the Kubernetes cluster. The result is an automatic dynamic configuration of the Argo CD.</p><p>Let’s consider the second option to solve the problem: using a powerful ApplicationSet tool.</p><h3>ApplicationSet: staying within the pull model</h3><p>Argo CD has ApplicationSet, its own tool for dynamically creating “application” within a pool model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*ZfgSAtg5DL2whlE6OAes8A.jpeg" /></figure><p>It allows you to create apps automatically instead of manually. For this you need two components:</p><p>1.<strong>Template</strong>, that is, a description of what to generate.<br>2.<strong>Rules</strong></p><p>Rules can be different: a list of values, clusters added to Argo CD, or a folder in Git. When we add a new chart to the Git folder, it automatically creates an “application.”</p><p>Important point: With the Argo CD, you can work with repositories of SCM, such as GitLab, GitHub, and Bitbucket. You can also monitor the appearance of new branches in them. Rules can be combined, that is you can do multiplication. For example, you can multiply clusters by a Git folder with charts. That way, a set of charts from this folder will be installed in each cluster.</p><h3>Examples of using ApplicationSet</h3><h4>Cluster setup</h4><p>Let’s say we have a production and a stage cluster and we want to add a dev cluster.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zX3jDDDZ3bQ9CxDAYkSa4Q.jpeg" /></figure><p>Usually after creating a cluster, we need to put infrastructure apps there. They are necessary for the correct work of developer apps. For example, Ingress controller, cert-manager, and monitoring stack to keep track of what is going on inside the cluster.</p><p>How does the ApplicationSet help here? We configure it to track a folder with charts and deploy those charts to all the clusters. When we add a new cluster to the Argo CD, it immediately starts deploying all these charts into it. The Ingress controller, cert-manager, and VictoriaMetrics will appear as an example of a monitoring stack. This way you can ensure that all clusters have the necessary set of infrastructure tools. There is no manual action here: except for adding a cluster, everything else will be done by Argo CD. If we want to add a new item to all the clusters, we just add it to the infrastructure charts folder and everything will be deployed automatically.</p><h3>Dynamic environments</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2mbHNoOLFY2ovjfjOzruBA.png" /></figure><p><strong>Example:</strong> There is a team of developers who work on two projects. They use a common methodology and develop features in separate branches with names like feature-&lt;task number&gt;. We create an ApplicationSet, configure it with the Gitlab group that contains these projects, and specify that you want to track the feature-* type branches. As a result, Argo CD will generate “application” entities for each individual developer branch.</p><h3>Full automation (extreme option)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uLVeuNgsuca3xlUXZm3wxA.jpeg" /></figure><p>This is an example for those who are not afraid to experiment. Here we create several ApplicationSet objects. Then the developer simply creates a project in the desired group. Argo CD and its ApplicationSets see that there is a new project in the group. They immediately deploy a production, stage, and dynamic environments for it when the developer creates branches in these repositories.</p><h3>How does ApplicationSet look like</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4ymq8RIoSp-U5LvEP82kPw.png" /></figure><pre>apiVersion: argoproj.io/v1alpha1<br>kind: ApplicationSet<br>metadata: ...<br>spec:<br> generators:<br>   - scmProvider:<br>       # ...<br>       filters:<br>         - branchMatch: ^feature<br>           repositoryMatch: ^backend<br>       gitlab:<br>         allBranches: true<br>         api: &quot;https://gitlab.team.ktsstudio.ru&quot;<br>         group: applicationset<br>         ...</pre><p>In the “generators” section, we specify the rules for generating “applications.” In this case, we specify GitLab, keep track of all repositories that start with “backend,” and deploy only branches that start with “feature.”</p><p>In the “template” section, we specify the template used to create the “application.” Note that you can use various ready-made variables from Argo CD inside (e.g. “repository” and “branch”).</p><pre>template:<br> metadata:<br>   name: &gt;-<br>     {{ printf &quot;{{ repository }}-{{ branch }}&quot; }}<br> spec:<br>   destination:<br>     namespace: &gt;-<br>       {{ printf &quot;{{ repository }}-{{ branch }}&quot; }}<br>     name: dev-cluster<br>   project: my-service<br>   source:<br>     # ...path, repoURL, targetRevision<br>     helm:<br>       parameters:<br>         - name: &quot;ingressHost&quot;<br>           value: &gt;-<br>             {{ printf &quot;{{ branch }}.example.com&quot; }}</pre><p>Generation example:</p><pre>apiVersion: argoproj.io/v1alpha1<br>kind: Application<br>metadata:<br> name: backend-auth-feature-1<br> namespace: argocd<br>spec:<br> destination:<br>   namespace: backend-auth-feature-1<br>   name: dev-cluster<br> project: my-service<br> source:<br>   # path, repoURL, targetRevision...<br>   helm:<br>     parameters:<br>       - name: &quot;ingressHost&quot;<br>         value: feature-1.example.com</pre><h3>The bottom line: pros and cons of the GitOps approach</h3><p>The classic push model uses CD Jobs everywhere, and you can only introduce changes through them. Hence the problem. For example, if you want to change the way a certificate is obtained, you have to go to each repository separately, make changes, run the pipelines, and only then everything is synchronized.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ew05VZlgZs3kte_DfOCjJA.png" /></figure><p>With the Argo CD you can remove this step. Argo only needs GitLab and the Docker Registry, by which it will generate “application” entities and update them. That is, with this tool we solve all synchronization problems.</p><h3>Pros and cons of the GitOps approach</h3><p><strong>Pros:</strong></p><ol><li><strong>Control over actions on the infrastructure.</strong> We can see all actions and control access to the infrastructure through GitLab.</li><li><strong>Constant synchronization.</strong>If someone makes changes manually, Argo CD will constantly try to roll them back. That is, we get protection from unnecessary edits. At the same time you can disable synchronization in the Argo CD. For example, if you need to test something.</li><li><strong>Easier management of a big infrastructure</strong> For example, Argo CD is very helpful when you need to add a new Ingress controller to each cluster of a sprawling infrastructure or to adjust the monitoring stack settings.</li></ol><p><strong>Cons:</strong></p><ol><li><strong>More complicated implementation.</strong> If you have one project and little infrastructure, it’s easier to use the usual pipelines and the push model.</li></ol><p>The next part of the report will be about managing the infrastructure itself using the new Crossplane tool. It will allow us to create any objects in the cloud and synchronize their state using a Kubernetes cluster only.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=121cfcf85290" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/gitops-platform-powered-by-argo-cd-121cfcf85290">GitOps Platform Powered by Argo CD</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The History of DevOps: From the Beginning of Time to ArgoCD and IaC]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/the-history-of-devops-from-the-beginning-of-time-to-argocd-and-iac-b9f97e0a9f72?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/b9f97e0a9f72</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[sermalenk]]></dc:creator>
            <pubDate>Wed, 24 May 2023 12:01:11 GMT</pubDate>
            <atom:updated>2023-05-24T12:34:14.832Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lugks4eShfyWKXhmmI6JxA.jpeg" /></figure><p>Hi, my name is Sergey, I am the head of the DevOps unit at <a href="https://www.lonto.io/">Lonto</a>.</p><p>We periodically partner with interesting guys and organize events together. The examples of such events are meetings of entrepreneurs, online flat parties, and product management days. This series of three articles is a text version of the speeches from the CTO Day event. The report has two speakers:</p><ul><li>Sergei Malenko, Head of DevOps unit at Lonto</li><li>Sergey Bondarev, Architect at Southbridge</li></ul><p>The report was devoted to the history of app deployment, the main models used for it, and their comparison. We discuss the pull model in detail and show how to use “advanced” tools to manage the infrastructure of large projects and allow developers to independently order elements in the infrastructure for the needs of their apps.</p><p>All in all, we have prepared three articles based on the report. They will follow this order:</p><p><strong>The history and how things evolved ←</strong>you are here 🚩<em><br>To understand the context, we will check out how the approach to iterative app deployment changed over time.</em></p><p><strong>What is ArgoCD and why do we need it, with use cases </strong><em><br>We’ll talk about a relatively new turn in the app deployment methods and see what questions can be solved with this tool.</em></p><p><strong>How to manage infrastructure in GitOps using Crossplane <br></strong><em>A new approach to IaC and how it can be combined with Argo CD</em></p><p>This part was prepared by Sergei Bondarev. Here, we will tell how coders used to work in the past:</p><ul><li>FTP protocol</li><li>Git</li><li>Assembly automation</li><li>Deployment automation</li><li>Kubernetes</li><li>Helm</li><li>Dynamic environments</li><li>Classic push model</li><li>Disadvantages of Helm</li><li>Pull models and GitOps</li><li>What’s next</li></ul><h3><strong>FTP protocol</strong></h3><p><a href="https://en.wikipedia.org/wiki/File_Transfer_Protocol">FTP is an old protocol</a> for transferring files over the network. It appeared in 1971, long before HTTP and even TCP/IP. The coders would write code on the computer, then FTP it to the server, and get the website. Strong coders wrote the code directly on the server, usually on the production:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c7GCisHQ313HR5Dgqb9dNA.png" /></figure><h3>Git</h3><p>When there became more code, they invented GIT: a place to store the code.</p><p>The programmers write code on their machine and send it to Git via Github/Gitlab. Then they connect to the server, run the “git pull” command there, get all the code they saved in the repository, restart the services, and the production stand gets updated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iXD3cycwB0N00mHcQB5PPg.png" /></figure><h3>Assembly automation</h3><p>Later they decided that it was a bad idea to put the code directly to the server. E.g. because someone might forget to do something manually.</p><p>So they started to compose packages for operating systems, like RPM or Deb, and store them in separate repositories and artifact collectors. They also started to automate this process.</p><p>That’s how they came up with the first CI: running automatic jobs over the push to the repository. The tasks were building packages and sending them to the repository. Then the coder would go to the server and install the package manually.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v6jIe2o0fYfoQCqEYB4szw.png" /></figure><h3>Deployment automation</h3><p>Then they decided to use a robot instead of a person who would perform the “yum install.” When the package is built, the robot connects to the server and runs a script, such as the Ansible script. This script performs the “yum install” and the production stand gets updated and restarted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vQmQAkzWUsdnzRlKTEvI7Q.png" /></figure><p>Later, Docker came along. It became possible to pack a project into an image, which is much easier to run on any OS. Unlike the specification for the RPM package which takes a long time to learn, the Docker file is a simple set of commands. With Docker, the user immediately gets a backup of the operating system. And the app works just fine in it. The package build is replaced with a Docker image build, it is pushed to the image repository, and after that the CD Job runs something like a “docker compose up.” All services are initiated on the same server:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ilMJJlT9uFIAGSfzvn_J5g.png" /></figure><h3>Kubernetes</h3><p>When a project grows, the issues of fault tolerance and lack of space on a single virtual machine arise. To address these issues, orchestrators were invented. The most popular of them is Kubernetes. The appearance of orchestrators brings a new approach: a microservice architecture. This approach assumes splitting huge services into separate ones with each of them responsible for their area only.<br>Now we can replace the docker-compose deployment by using kubectl in a CI job and keep the automation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXq7NRnkOr2G0sFGWOYQqA.png" /></figure><p>You can check out our <a href="https://medium.com/kts-digital-services-integrator/kubernetes-and-other-orchestrators-3db33af1e44f">article about Kubernetes and other orchestrators.</a></p><h3>Helm</h3><p>Let’s imagine that you have many projects, and YAML manifests for Kubernetes are similar to each other. They can be templated, which is why <a href="https://helm.sh/">Helm</a> is connected. It helps to manage the apps installed in Kubernetes.</p><p>You need to replace the application via the kubectl apply with helm upgrade and install the apps in Kubernetes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57UdjS34L5DJj4ijXL80hA.png" /></figure><p>At some point, the coders are no longer satisfied with only one cluster for production. They want a full-sized environment that is like a production environment, but not exactly. They need it to test new versions and do integration testing. DeVops make a second Kubernetes cluster, put a domain like <a href="http://test.example.com/">test.example.com</a> on it, and give it to coders. It goes like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8uAAMtAZxrbn6zKAPlNUhQ.png" /></figure><p>The coders try it, but it turns out that there were too many development teams. They need a lot of stands for everyone to be able to work with their test cluster. DevOps make five stands manually. So they end up with one production cluster and one test cluster with five different namespace stands for environments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7cQMHntfbVGpbkp0EoCE0A.png" /></figure><p>It turns out that five stands are not enough. The development team grows and develops many more features in parallel. So coders have to wait for each other to get access to a freed up stand.</p><h3>Dynamic environments</h3><p>Stands are made dynamic: they are initiated for each feature automatically. We add the “build environment” step to the CI/CD Job. Now, when a coder wants to make a new feature and creates a new branch in the repository, the testing and development environment are initiated for it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TLEV_Z0HXrZ9YHrpsCE3Kw.png" /></figure><h3>Classic push model</h3><p>If we compress the pattern of dynamic environments, we get a classic push model.</p><p>The “push the code to repository” event starts the process. This process builds the environment for testing/production, assembles the project and artifacts, starts the process of deploying the project to this environment, and tests it. As a result, the app is automatically deployed to different environments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yLxEmgDKD0gEQF7_K1HoA.png" /></figure><h4>Advantages</h4><p><strong>Easy to implement.</strong> Uses a traditional approach with known utilities. This model is the easiest to implement within the team in the company.</p><p><strong>Versatile.</strong> You can deploy models for any load and achieve versatility in CI/CD approaches. The push model is easy to adapt and is often used for CD. It is convenient because the CD is a script in Bash or another automation language. It performs commands that you would otherwise do manually: “kubectl apply”, “helm upgrade”, and so on…</p><p><strong>Easy to expand.</strong> In real life, the pattern develops to this scale:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*cFfUmA4ufrcacZu4eR3iUg.jpeg" /></figure><h4>Disadvantages of Helm</h4><p>Helm is intended to be a template for YAML manifests and a deployer of those manifests into Kubernetes clusters. Helm is good at making YAML manifests from templates. But there may be problems when transferring them to a Kubernetes cluster.</p><p><strong>Inane errors.</strong> Those who have worked with Helm have probably seen errors like this:</p><pre>Error converting YAML to JSON: yaml: line 12: did not find expected key</pre><p>It is not clear in which file and which template this line 12 is. The template in YAML can sprawl over two hundred lines. The only option you have is to use the trial and error method, that is to go to the templates and cut off half of them. Then you check out if the error remains and look for it that way.</p><p><strong>You can’t check out the logs of the failed pods. </strong>Those who used Helm Chart with a “wait” parameter had a similar case. The coders wait for the pods to rise in the chart and for the chart setup to complete. They usually specify the “atomic” key, which allows you to roll back if the installation fails. The coders put a “wait” of 500 seconds and the “atomic.” The process of deploying the chart initiates. 500 seconds go by, suddenly the release doesn’t install, and everything rolls back:</p><pre>kubectl logs admin-687fcb89ff-knk93<br>Error from server (NotFound): pods &quot;admin-687fcb89ff-knk93&quot; not found</pre><p>It turns out that log collection is centralized. You have to look for them with Kibana: by time, namespace, and pod name. Maybe you’ll find something…</p><p>You can’t check out the logs of the pod with the simple kubectl logs command, because by this point Helm has already deleted all the pods that were in the CrashLoopBackOff state and have not become “ready.” Helm does it to roll back to a previous release.</p><p>This problem can be solved by Helm hooks. They are triggered if a release which pulls logs from the failed pods has not passed. But here comes another problem: time-outs.</p><p><strong>Pending-upgrade status.</strong>We set a timeout of 500 seconds. If the hook does not work within 500 seconds, the chart gets the “pending upgrade” or “pending install” status:</p><pre>helm ls -a<br><br>NAME    NAMESPACE  REVISION  UPDATED    STATUS                CHART                                <br>admin     dev23                    3            2022-07-25  pending-upgrade  admin-3.3.1 </pre><p>This is the worst thing that can happen to Helm. After that it refuses to work with the chart and hangs up. The CI is launched for the second time with the “helm upgrade” command. It results with an error and says that someone is already working with the chart.</p><p>It turns out that there is a process that keeps track of what is going on in the cluster. After that, it gets finished, does not clean up after itself, and remains in a suspended state. The second time it starts up and kind of tells: “Someone is working there, I don’t know who, but I won’t do anything just in case.”</p><p>To solve this problem, you need to delete the whole chart or do the Helm Rollback: manually rollback the release to the previous one. But these are the manual operations that break automation at its roots.</p><h3>Pull models and GitOps</h3><p>We have a CI system: developers push into it, then the pipelines go into the infrastructure and change something. For example, the database or ingress-controller connection settings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1yLxEmgDKD0gEQF7_K1HoA.png" /></figure><p>In the pull model, the situation is somewhat different. There appears a repository in which developers or admins store the configuration. An additional element is added: the agent. Its task is to synchronize the state that is described in the repository with the infrastructure.</p><p>GitOps is one of the implementations of the pull model. Git acts as a repository for all configurations in it. The source of truth is Git. It is the only point through which the changes to the infrastructure are done. Then the agent applies the changes and maintains the given state.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IWKkpnAM_Hg3hZ8U5V8LIw.png" /></figure><p><strong>Features of the GitOps model:</strong></p><ul><li>The source of truth is Git</li><li>All actions are done through Git only</li><li>An agent that synchronizes the state is added</li></ul><p>Let’s say we changed something manually in the infrastructure. For example, the number of replicas of the app. The agent will realize that this does not match with the settings written in the source of truth and will return everything to its original state.</p><p><strong>Advantages of the pull model:</strong></p><ul><li>All changes go through Git, so you can find out who made them and check out the commit text to learn what they were made for (if you’re tracking that, of course)</li><li>A guarantee that the deployment in your infrastructure is exactly the same as described in this repository. In the case of the push model you cannot understand the state, because everything is applied from different CD Jobs</li><li>Easy to make changes to multiple projects at once: everything you need is in the repository</li></ul><p><strong>Tools:</strong></p><ul><li>ArgoCD</li><li>Flux</li><li>Weaveworks</li></ul><p>In the next article, we will take a closer look at ArgoCD, since it is the most popular tool that implements the GitOps approach.</p><h3>What’s next</h3><p><strong>In this part,</strong> we’ve described how approaches to deploying apps evolved and had a brief glance at the GitOps model, an alternative to the classic push model.</p><p><strong>In the second part,</strong> we will explain how the Argo CD works and how the GitOps approach works.</p><p><strong>In the third part,</strong> we’ll tell you how the infrastructure is managed.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b9f97e0a9f72" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/the-history-of-devops-from-the-beginning-of-time-to-argocd-and-iac-b9f97e0a9f72">The History of DevOps: From the Beginning of Time to ArgoCD and IaC</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Figuring Out Asynchrony: When It’s Useful And When It’s Not?]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/figuring-out-asynchrony-when-its-useful-and-when-it-s-not-d6916fdcd273?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/d6916fdcd273</guid>
            <category><![CDATA[async]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[artbakulev]]></dc:creator>
            <pubDate>Mon, 22 May 2023 11:46:13 GMT</pubDate>
            <atom:updated>2023-05-22T11:46:13.216Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRHd8HQyzwHK2f2EEt_Ylw.jpeg" /></figure><blockquote>“The worst part is the waiting and not being able to do anything. It drives you crazy and does you in”</blockquote><blockquote><em>E.M. Remarque</em></blockquote><p>Hi! My name is Artyom, I am a backend developer at <a href="https://www.lonto.io/">Lonto</a>. I do projects where asynchronous programming is ubiquitous, and I also teach courses on it at our Metaclass school.</p><p>Today I’ll try to explain what asynchronous programming is, why you need it, what problems it solves, and how to learn it. Since my primary language is Python, the article will be Python-oriented.</p><p>Form the article you will know:</p><ul><li>What is asynchronous programming?</li><li>What are the other options for solving the problem of blocking while waiting</li><li>When asynchronous programming is useful</li><li>Example 1. Creating a file repository</li><li>Example 2: Chatbot</li><li>When asynchronous programming is useless</li><li>Is it important to know how to write asynchronous code nowadays</li><li>Why write asynchronous code in Python</li><li>Speed and ease of development</li><li>Popularity of the language</li><li>Summary</li><li>Where to begin learning asyncio</li></ul><p>Let’s go! 🚀</p><p>In order to understand the article more clearly, two ladies volunteered to help us: Synthie and Asya. <strong>Syn</strong>thie promotes the <strong>syn</strong>chronized lifestyle, while <strong>Asy</strong>a prefers the <strong>asy</strong>nchronous approach. I will try to illustrate the differences between asynchronous and synchronous approaches with everyday examples involving these two ladies, and then provide a real case study from the dev world.</p><h3>What is asynchronous programming</h3><p><strong>Let’s start with an everyday life example</strong></p><p>Synthie and Asya had a competition to see who would be the first to cook a roast chicken. To do the cooking, they have to buy chicken and vegetables from the nearest store. And, unfortunately, there’s no no self-service there.</p><p>🔵 Synthie went to the store first. She asked the sales clerk to weigh the chicken and watched the weighing process closely. The clerk weighed the chicken for one minute and then gave it to Synthie. After that, Synthie went to another department and watched the other clerk while he weighed her vegetables for one minute. As a result, Synthie spent two minutes in the store, not counting the time at the cash register.</p><p>🟠 On the other hand, Asya asked to weigh the chicken, and then went to another department and asked to weigh the vegetables. She <em>did not wait</em> for the first clerk to finish weighing. Asya browsed the store shelves for a minute, and then the meat clerk called out to her. Immediately thereafter, the vegetable clerk did the same. Asya ended up spending only one minute in the store.</p><p>In the world of development there are often tasks that require you to get data from external sources. In the example above, the data is vegetables and chicken.</p><p><strong>Now let’s move on to dev examples</strong></p><p>You’ve created a website that displays tomorrow’s weather forecast. Of course, you don’t have your own weather station in your yard. So, to know the temperature and wind speed, you need to send a query to some service that can provide this data.</p><p>So how will the different approaches above send this query and handle the response?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8H7WMnjJDi1oG10gK1_DAg.jpeg" /></figure><p>Let’s check out the illustration above.</p><p><strong>🔵The synchronous approach is shown on the left.</strong> The synchronous program sends a query. And it can’t do other useful work while it waits for the results of this query. The program will only be able to continue when it receives a response from the external server, because its further actions depend on external data.</p><p><strong>🟠The asynchronous approach is on the right.</strong>An asynchronous program first behaves the same as a synchronous one: it sends a query to the server. But then its behavior is drastically different: it does not block while waiting for results. It performs some other actions that do not require a response from the external server. When the server returns a response, it can return to further processing of the received data.</p><p><em>Asynchronous</em> programming aims to keep the program idle for as little time as possible while waiting for some external event to happen. In other words, the main problem with <em>synchronous</em> approach is “idle waiting.”</p><h4>What are the other options for solving the problem of blocking while waiting</h4><p>Of course, asynchronous programming is not the only approach that lets you avoid blocking while waiting for a response. Let’s check out an everyday life example again.</p><p>Imagine that in the previous example there were twin sisters: Synthie_1 and Synthie_2. They came to the store and one of them went to the vegetable department, while the other went to the meat section. Their total time in the store will be the same as Asya’s — one minute. But the second Synthie needs resources to exist: she needs at least somewhere to live and something to eat in order to do shopping.<br>A bit exaggerated, we can say that Synthie_1 and Synthie_2 use <strong>parallelism</strong> to go to the store.</p><p><strong>Parallelism</strong> is an approach when code is run in a new <em>computer process or thread</em>. That is, several operations are executed <em>in parallel</em> and cannot be interrupted by some other task. In this case we are talking about synchronous implementation of the program within such parallel threads/processes.</p><p>This explanation may seem somewhat complicated and incomplete, but the main idea should be clear: to apply this approach in practice, you need to create an additional entity (process or thread). Additional entities require extra resources for their maintenance, although they generally perform the task in the same amount of time as the asynchronous approach. Of course, it would be wrong to say that parallelism is inefficient, but we will discuss the exact cases when it is effective below.</p><p><strong>It is important</strong> to distinguish between the concepts of <em>single-threaded/multi-threaded</em> and the concepts of <em>synchronous/asynchronous</em>. There are all kinds of combinations of these concepts out there. For example, you can write a multi-threaded asynchronous program. It would resemble a situation when two Asyas go to the store instead of two Synthies. In this article I talk about a single-threaded asynchronous approach based on the principle of <a href="https://en.wikipedia.org/wiki/Cooperative_multitasking">cooperative multitasking</a>, because it is the principle used in asyncio and the one that takes GIL limitations into account. Thus, Asya is a <em>single-threaded</em> asynchronous approach, and Synthie is a <em>single-threaded</em> synchronous approach.</p><h3>When asynchronous programming is useful</h3><p>Tasks where the asynchronous approach is efficient are called I/O-bound tasks, where I/O stands for Input/Output and bound is a constraint. That is, these are tasks whose execution time is mainly regulated by the execution time of all input/output operations. I/O operations are usually network and file system operations. It is important to understand that the asynchronous approach doesn’t optimize these operations’ execution time individually. It optimizes the program’s <em>total runtime</em>, and the program usually consists of many such operations.</p><p>In the world of web development, there are especially many operations that require waiting. Let’s take a look at some of the tasks that can be effectively solved using the asynchronous approach.</p><h4>Example 1. Creating a file repository</h4><p>Let’s say that you’ve been tasked to create a file hosting service — an analogue of Google Drive. The user uploads a file, and the service gives them a link where the file can be downloaded. Let the service save the file to your hard drive, and paste the mapping (path to the file):(link where it is available) into the database.</p><p>We see two obvious I/O-bound operations in this task: querying an external database and writing a file to a disk. In addition, there are some non-obvious I/O-bound operations here: receiving the file in full from the user (this happens in chunks) and distributing the file when it is downloaded by the user (also in chunks). These chunks’ length is determined by the data transmission protocol on the Internet.</p><p>🔵 In the single-threaded synchronous approach, the service will process only one query, i.e. one user, at a time. The synchronous service will first have to wait for the file to arrive on the network card, then save it to the file system, get a response from the database, and then give the user the generated download link.</p><p>🟠 In the asynchronous approach, the service will be able to handle many queries at once <em>competitively</em>, constantly switching between them when new data gets available.</p><p>For example, if the user sends a piece of a file, the service will save it to the hard drive. If they get a response from the database, the service will send the user a link to the file, and so on.</p><p>What happens if a user who wants to download a 40 GB movie in 4K quality comes along?</p><p><strong>Let’s check out an everyday life example first</strong></p><p>Let’s imagine that Asya and Synthie want to make some coffee with their new coffee machine. They don’t know how to use it, so they read the instructions. In the instructions, the algorithm is described point by point.</p><p>🔵 Synthie first reads all the points, memorizes them completely, and then starts making coffee.</p><p>🟠 Asya choses a different approach: she reads one paragraph of the instructions, then follows and immediately forgets it.</p><p>As a result, Asya stores less information (only one paragraph of instructions) and can switch to another task at any moment of waiting, and then get back to making her coffee.</p><p>🔵 Single-threaded synchronous service will face two problems at once. First, the service will not be able to process other queries until it is done with the 4K 40GB. There is also another non-obvious problem. When using standard approaches, you will have to first wait until the entire file is loaded into the server’s RAM (that is, in the case of Synthie, read and remember the entire instructions). And only after that you can start processing it. Even nowadays, a 40 GB RAM server is quite a luxury.</p><p>🟠 Asynchronous service can <em>stream</em> a file to the repository right away — in chunks. That is, when we receive a new data chunk, it makes no sense for us to keep it — if the end goal is to write it to a disk. We can immediately save it to the disk and clear the memory. Thus, our program’s memory size will always stay more or less the same, regardless of the size of the resulting files. In addition, we can process each chunk asynchronously (that is to interrupt after the next item of instruction is executed, to use the analogy with the example above). For example, you can report the current progress of a file download via the websocket channel.</p><h4>Example 2: Chatbot</h4><p>Some technologies do not suppose using a purely synchronous approach at all. For example, we need a chatbot that receives a message and sends a reply to it.</p><p><strong>An everyday life example</strong></p><p>Let’s recall the example with the store and imagine that the chicken is being unloaded into the warehouse right now and the clerk can’t weigh it until the unload is over.</p><p>🔵 Synthie has two options:</p><ul><li>ask the clerk once and stand for a long time waiting for the chicken to be given to her, i.e. the unloading process is complete;</li><li>keep asking if she could finally get the chicken, much to the seller’s annoyance.</li></ul><p>In the first case, Synthie will waste time, and in the second — her nerves.</p><p>In the first case, Synthie used the Long Polling approach, and in the second it was just Polling. Let’s figure out what these approaches are and how they relate to chatbots.</p><p><em>Long Polling</em> is a method when we send a “long” HTTP query to the social network server and receive new messages in response to that query. “Long” means that the social network will only return a response to us in two cases: when a new event occurs or the waiting time expires. I.e. we have to wait for a response for a long time. In many social networks we can get messages using this option, for example in <a href="https://vk.com/dev.php?method=bots_longpoll">Telegram</a> and in <a href="https://vk.com/dev.php?method=bots_longpoll">VK</a>. And this is the approach we use in our <a href="https://www.smartbotpro.io/">Smartbot Pro</a> bot builder.</p><p><em>Long Polling</em> is ineffective in a single-threaded synchronous approach, because the program will simply be blocked while waiting for a response from the server (which is usually 30–60 seconds, if there are no new events). If you have one bot only, this solution has a right to life. But if you want to handle two bots at once, you first need to finish the query to the first bot, then process the message it receives, then finish the query to the second bot and so on… So, in the worst case, the user will write their message as soon as the bot query is finished and wait 30–60 seconds before getting a response.</p><p>We can use Polling and respond much faster by constantly asking the server: “Are there any new messages?” The server will answer instantly that “No, there are no new messages” or “Yes, here are new messages”, but in this case we will waste time to constantly establish connections and send a lot of “useless” queries.</p><h3><strong>When asynchronous programming is useless</strong></h3><p><strong>Let’s check out an everyday life example:</strong></p><p>The company where Synthie and Asya work gave them a present for Christmas: jigsaw puzzles.</p><p>🔵 Synthie took the puzzles and began to put them together methodically, without distractions on anything else. In the end, it took <em>one hour</em> to assemble the puzzles.<br>Everyone knows that Synthie doesn’t like to be distracted, so no one was offended that she didn’t answer the chat for an hour.</p><p>🟠 Asya also took the puzzles and began to put them together, but because of her somewhat restless nature, it took her a little more self-control to put them together in the same <em>one hour</em>. That said, people who were used to her responding in the chat quickly got offended that she didn’t reply.</p><p>Both ladies assembled the puzzles in one hour, but Synthie’s process was a little more efficient. Tasks such as jigsaw puzzles can be called<strong> CPU-bound</strong> <strong>operations </strong>in the programming world.</p><p>💡 <strong>CPU-bound operations</strong> are tasks that fully utilize computational resources. That is, these tasks are limited to the CPU’s performance rather than waiting for external resources’ replies.</p><p>Can we perform such tasks in a service created in an asynchronous paradigm? Yes, we can, but it won’t be quite right.</p><p>First, the asynchronous approach requires a scheduler component that will continue to execute the pending code when external events occur. It is usually called an <em>event loop</em>. In CPU-bound operations, this component is useless, but we still spend time on its creation and operation.</p><p>Second, an asynchronous service is usually written to interact with many operations at one point in time. So, some users can get “offended” that such a service does not respond to them because it performs a long synchronous operation. It is a common rookie mistake to perform long calculations when the query is processed. It results in the service stopping to respond to other queries and “pretending” as if it has hung up.</p><p>The examples of CPU-bound operations are sorting large amounts of data, training ML models, archiving files, etc. That is the exact case when parallelism is useful. That is, when the help of Synthie_2 or, in other words, the possibility of distributed parallel computing on several processor cores or on many processors is effective.</p><p>Is it important to know how to write asynchronous code nowadays</p><p>Support for modern development principles</p><p>Let’s start from afar and look at how the Web has developed in general.</p><p>In the early days of the Web, all services were monolithic: there was one big entity in which all the business logic of the service was implemented. Over time, people realized that monolithic architecture is not always the best solution. Because of this architecture, the overall resilience of the app suffers, the development speed often decreases, and you can’t efficiently scale it.</p><p>Many projects are now written or rewritten based on the principles of microservice architecture. A distinctive feature of this approach is the huge amount of crossrequesting from microservice to microservice or from microservice to database. And as we know, queries are I/O-bound operations and the asynchronous approach works just well with them. So if you’re building an app with a microservice architecture, you’ll probably need to use an asynchronous approach.</p><p>Development of libraries and frameworks towards asynchrony</p><p>Django is probably the best illustration of the world moving toward an asynchronous approach. Not long ago it was a fully synchronous framework. Asynchrony support has been added since version 3 and is now becoming more and more comprehensive. That is, even if you write projects in most likely the most common Python framework, you need to know the principles of asynchrony.</p><p>Many services were originally written in a synchronous paradigm. Instagram, for example. It was written in a synchronous version of Django. But how did it cope with the heavy load? Props to the Instagram team: long before Django became asynchronous, they rewrote the app’s core and added asynchrony support.</p><p>The fact that Python added asyncio to its standard asynchronous operations library in 2015 speaks volumes: the Python kernel development team understands that this is the future of development. Or, in fact, it’s already the present. Every year more and more frameworks and libraries for asynchronous programming are released. Developers write either an analogue for “old” synchronous modules (e.g. <a href="https://github.com/igorcoding/asynctnt">asyntntnt</a>) , or add asynchronous logic to them.</p><p>If you want to be on a team that rolls out big, modern projects, the knowledge of synchronous approach alone probably won’t be enough. If you want to be a part of some big project that will handle a heavy workload, chances are you’ll need to be able to write asynchronous code.</p><h3>Why write asynchronous code in Python</h3><h4>Speed and ease of development</h4><p>Many have heard that Python is a relatively slow language. It is logical to assume that you should immediately learn the asynchronous paradigm in a more efficient language, but it is not so unambiguous. Let’s take Golang as an example and start with an everyday life example.</p><p>Asya decided to learn knitting and came to the master class. The same master class was attended by the entire <strong>Go</strong>lan family.</p><p>🟠 Asya quickly learned to knit, although she still knits slowly. It only took her one class and a novice teacher to learn.</p><p><strong>🟣</strong>The <strong>Go</strong>lans decided to knit several things at once, while also helping each other. It took them an experienced teacher (whose classes were more expensive) and five classes to get this close interaction working. Still, they learned how to knit very quickly.</p><p>In the end, it took Asya the least amount of resources to learn, and she is productive enough to knit presents for her friends. It took the <strong>Go</strong>lans several times as much time and money to set up their work, but they can do 10 times as many things as Asya in the same amount of time.</p><p>After the master class, it turned out that the <strong>Go</strong>lans just didn’t have that many friends to knit for them with the entire family and at the same time. Therefore, they are unlikely to start working at their maximum capacity in the near future. Besides, if Asya realizes that she is falling behind, she can easily ask the <strong>Go</strong>lans to help her.</p><p>Developing in Python is similar to the example above: it takes less time and experience to create a working product. You can write asynchronous Python code with asyncio even without knowing about synchronization primitives: mutexes, semaphores, atomics, and so on. You can practically forget about race conditions either. With asyncio you write code that looks synchronous. Of course, the more immersion, the more nuances appear. But the code for basic tasks is very easy to write. This is largely thanks to <a href="https://realpython.com/python-gil/">GIL</a>, which removes the developer’s responsibility for competitive memory access.</p><p>In Go, on the contrary, you should always make sure that the shared memory is used correctly. In other words you should ensure <em>thread-safety</em>. In the words of the example above, each member of the <strong>Go</strong>lan family needs to knit exactly the right piece and not sew a third sleeve to the sweater, not knowing that there are already two. This slows down the development, and bugs become more difficult to diagnose and fix.</p><p>In any case, if the speed becomes very important at some point of the program, you can take this part out as a separate microservice written in a more efficient programming language. Or write it in C and embed it in Python. For example, <a href="http://magic.io/blog/uvloop-blazing-fast-python-networking/tcp-bench.html">here are some benchmarks</a> of the UVLoop server, an event loop written in C and built into Python as a library. There is also a comparison with Go there.</p><h4>Popularity of the language</h4><p>If you look at the <a href="https://www.tiobe.com/tiobe-index/">TIOBE</a> languages popularity index, based on user search queries, the number of qualified programmers in the language, and other factors, you can see that Python is in the first place.</p><p>The popularity of Python means that:</p><ul><li>There are more tutorials for it.</li><li>If you have a specific problem, you are more likely to find an answer on Stack Overflow specifically for Python.</li><li>More people learn and understand Python in parallel with you. So, there is a large community in which you can ask a question and get a qualified answer.</li><li>More jobs and more projects. For example, there are currently 5,000 Python developer jobs open in Moscow and only 600 in Go.</li></ul><h3>Summary</h3><ul><li>Asynchronous programming shows its effectiveness only where I/O-bound operations prevail. In CPU-bound operations, the asynchronous approach is useless and even harmful.</li><li>You should distinguish between the concepts of synchronicity/asynchrony and single-threaded/multi-threaded approach.</li><li>An advantage of an asynchronous program is that it can handle as many I/O-bound operations in one thread as the multi-threaded synchronous one. Meanwhile, it will consume minimal resources and, in most cases, finish the task in less time.</li><li>There are technologies that do not suppose a single-threaded synchronous approach, such as Long Polling or streaming.</li><li>Complex and modern projects use microservice architecture in most cases. This architecture presumes many I/O-bound operations, and hence an asynchronous approach to process them.</li><li>Python has many asynchronous modules that cover all needs to create almost any project.</li><li>To speed up specific parts of the program, you can create a separate microservice in a more efficient language or write your own binding directly in Python in Cython.</li><li>Python is currently the most popular language in the world.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d6916fdcd273" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/figuring-out-asynchrony-when-its-useful-and-when-it-s-not-d6916fdcd273">Figuring Out Asynchrony: When It’s Useful And When It’s Not?</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Kubernetes and Other Orchestrators]]></title>
            <link>https://medium.com/lonto-digital-services-integrator/kubernetes-and-other-orchestrators-3db33af1e44f?source=rss----d9314f378ff---4</link>
            <guid isPermaLink="false">https://medium.com/p/3db33af1e44f</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Leo Gvozdkov]]></dc:creator>
            <pubDate>Fri, 28 Apr 2023 12:31:44 GMT</pubDate>
            <atom:updated>2023-05-19T10:39:00.956Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nZrMQxUT60isjqgVJgkWbA.jpeg" /></figure><p>Hi! My name is Leonid, I am a DevOps engineer at KTS.</p><p>In this article, I will review different orchestrators and explain why Kubernetes is the best choice.</p><p>Our company is 6 years old, and we’ve been living with Kubernetes for 4 of them. Before that, we tried all kinds of app deploy options on the servers: starting with a simple git pull up till ci/cd on multiple servers.</p><p>In the short period of four years we have gained a lot of experience. We started with the question you may be facing right now: “Which orchestrator to choose?” We considered different options, and in the end we settled on Kubernetes. In this article I will tell you why.</p><p>What’s in the article:</p><ul><li>What is an orchestrator and what tasks it performs</li><li><strong>Docker Swarm</strong></li><li><em>Architecture</em></li><li><em>Pros</em></li><li><em>Cons</em></li><li><strong>Nomad</strong></li><li><em>Architecture</em></li><li><em>Pros</em></li><li><em>Cons</em></li><li><strong>Kubernetes and OpenShift</strong></li><li><em>Architecture</em></li><li><em>Pros</em></li><li><em>Cons</em></li><li>How to start using</li><li>Conclusion: our case</li></ul><h3>What is an orchestrator and what tasks it performs</h3><p>Many of you must have heard of the microservice architecture.</p><p>Most microservices are containers that have to work together cohesively. In addition to containers, these can be the usual apps: for example, in Java or on a virtual machine.</p><p>The orchestrator allows you to centralize the management:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plMLzonLWujytNDfJa2lwA.jpeg" /></figure><p>What a good and handy orchestrator should have:</p><ul><li><strong>The ability to get started quickly</strong>, so you don’t have to spend half a year studying and testing.</li><li>A set of certain features right out of the box:<br>— <strong>Managing secrets:</strong> the ability to pass tokens, passwords, and database accesses to the app, rather than storing everything in code.<br> — <strong>Service discovery:</strong> the ability to connect new app replicas to the infrastructure.<br> — <strong>Cluster customization:</strong> the ability to add our entities and organize APIs for our purposes.</li><li><strong>Least possible vendor lock-in.</strong> When developers bind the buyer to a particular technology, switching vendors becomes very difficult.</li></ul><p><strong>Horizontal scaling:</strong> automatic scaling of cluster nodes and the app. The workload can be non-linear, so the orchestrator should be able to increase the number of app replicas on the go. If the cluster lacks resources, you should be able to increase.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUbGo6cmGgmUlflz0Scf4Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eEedS8P5knnE3hN1tDiv1w.jpeg" /></figure><p><strong>Vertical scaling:</strong>the cluster manages the resources that are allocated to the app. Ability to allocate and limit resources is necessary to avoid situations when one of the apps has consumed all the memory and CPU on our servers, and others are left with nothing. The orchestrator understands the initial resource limits for the app, and how much they can grow.</p><ul><li><strong>Different strategies for updating the app:</strong> the apps are constantly updated. Orchestrators have different strategies to ensure that this goes unnoticed by the user and the business, and that the updates themselves don’t crash in the process:<br><strong>– Rolling:</strong> a new version of the app is rolled out gradually. For example, we have 5 replicas of an app that gradually replace the original one, until finally the new version takes the place completely.<br><strong>– Recreate:</strong> a fairly simple strategy where we just kill the old version and roll out the new one.<br><strong>– Blue/Green:</strong> we roll out two versions of an app at once: while one works, the second is being tested and will eventually replace the first.<br><strong>– Canary (Dark):</strong> quite similar to Blue/Green, but with one peculiarity. The new version is rolled out to a limited number of users first. If there are no problems, we will gradually replace the entire app with the new version.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hrzR3fdwcRufkESU4liomQ.jpeg" /></figure><p><strong>Infrastructure as Code (IaC) with templating mechanisms:</strong> is a handy thing that lets you store app states, that are described by the code, in some manifests. It is convenient for both the engineers and the newcomers. When a company hires a newcomer, it’s easy for them to get familiarized with the infrastructure and understand how things are set up. And everything is conveniently versioned. We need templating to reuse manifests and not to write the same thing again and again. For example, we substitute different values in prepared templates and change the versions of the app:</p><pre>apiVersion: apps/v1<br>kind: Deployment<br>metadata:<br>  name: {{ .Values.name }}<br>  namespace: {{ .Values.namespace }}<br>  labels:<br>    app: {{ .Values.name }}<br>spec:<br>  replicas: {{ .Values.replicas }}<br>  strategy:<br>    type: RollingUpdate<br>    rollingUpdate:<br>      maxSurge: 1<br>      maxUnavailable: 0<br>  selector:<br>    matchLabels:<br>      app: {{ .Values.name }}<br>  template:<br>    metadata:<br>      labels:<br>        app: {{ .Values.name }}<br>    spec:<br>      containers:<br>      - name: {{ .Values.name }}<br>        image: {{ .Values.image }}<br>        ports:<br>          - containerPort: {{ .Values.HTTP_PORT }}</pre><ul><li><strong>A large community</strong> is the lifeblood of technology and tool diversity. As long as there is a community, the technology will live on.</li></ul><h3>Docker Swarm — orchestrator built into Docker</h3><p>Architecture and description:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_IfmGiq-dzUMQ9oWpLOWxg.jpeg" /></figure><p>Docker Swarm consists of managers and workers. Managers determine on which workers and how the containers will run. They also store the state of the cluster.</p><p>The Docker Swarm’s minimum working entity is a Service, which is broken down into tasks. Each task has a Docker container:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fZ0BjveLDq8UPdrUTDi7dA.jpeg" /></figure><p>In order to run some kind of Service, we need to:</p><ol><li>Run a YAML file, which is very similar to Docker Compose. The only difference is a few parameters specific to Swarm. For example, replicas.</li><li>Run a command that is very similar to the command for Docker Compose.</li></ol><pre>version: &quot;3&quot;<br> <br>services:<br>  proxy:<br>    image: nginx:latest<br>    ports:<br>      - 80:80<br>      - 443:443<br>    networks:<br>      - proxy<br>    deploy:<br>      replicas: 1<br>  <br>  frontend:<br>    image: kts/my-super-web:latest<br>    networks:<br>      - proxy<br>    volumes:<br>      - /opt/images:/usr/share/nginx/images<br>    deploy:<br>      placement:<br>        constraints: [node.role == worker]<br>      replicas: 3<br>   <br>networks:<br>  proxy:<br>    external: true</pre><pre>$ docker stack deploy --compose-file docker-compose.yml stackdemo</pre><h4>Pros</h4><ul><li>Completely free</li><li>Not demanding resource-wise</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v3KhNCGH1R_Href0uNmDLw.jpeg" /></figure><p>Has Roling Back — the ability to roll back the app to the previous version, if problems arise.</p><ul><li>Low entry level: simple initial setup. You only need to run two commands:</li></ul><p>1. To initialize а cluster:</p><pre>$ docker swarm init --advertise-addr 192.168.99.100</pre><p>2. To add virtual machines to the clusters:</p><pre>$ docker swarm join --token %sometoken% 192.168.99.100:2377</pre><h4>Cons</h4><ul><li>Only supports Docker containers</li><li>Does not support automatic scaling at all. You will have to create the number of app replicas manually in the replicas parameter:</li></ul><pre>$ docker service create --name my_web \<br>                        --replicas 3 \<br>                        --publish published=8080,target=80 \<br>                        nginx</pre><ul><li>Supports the Rolling Update strategy only.</li><li>Not much support from the community. Many have heard the phrase “Docker Swarm is dead.” The technology is not popular among specialists, it has few ready-made solutions.</li><li>We write the manifest language in YAML, but Docker Swarm has no built-in support for templates.</li></ul><h3>Nomad — orchestrator by HashiCorp</h3><p>Quite similar to Docker Swarm:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MK3JbW35k-UmZyE0YhZ8Nw.jpeg" /></figure><p>It consists of the servers that determine where and how the orchestration objects live, and the clients on which those objects run.</p><p>Unlike Services in Docker Swarm, in Nomad we create job entities. In their turn, they consist of task entities.</p><p>To create a job, we write a manifest and pass it to the server, which then distributes it to the clients.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGRbd3PGG5xbPOgWmSnX0g.jpeg" /></figure><pre>$ nomad job run example.nomad</pre><pre>job &quot;example-job&quot; {<br>  type = &quot;service&quot;<br>  update {<br>    stagger = &quot;30s&quot;<br>    max_parallel = 1<br>  }<br>  group &quot;example-group&quot; {<br>    count = 3<br>    task &quot;example-task&quot; {<br>      driver = &quot;docker&quot;<br>      config {<br>        image = &quot;nginx:latest&quot;<br>        <br>        port_map {<br>          http = 8080<br>        }<br>      }<br>      service {<br>        port = &quot;http&quot;<br>        check {<br>          type = &quot;http&quot;<br>          path = &quot;/&quot;<br>          interval = &quot;10s&quot;<br>          timeout = &quot;2s&quot;<br>        }<br>      }<br>      resources {<br>        cpu = 500<br>        memory = 128<br>        <br>        network {<br>          mbit = 100<br>          port &quot;http&quot; {}<br>        }<br>      }<br>    }<br>  }<br>}</pre><p>Nomad fully supports the entire HashiCorp ecosystem:</p><ul><li><strong>Vault</strong> for storing secret passwords, tokens, and more</li><li><strong>Consul</strong> for auto-discovery and dns</li><li><strong>Terraform</strong> for configuration management</li></ul><p>Another feature of Nomad is that it can manage GPU resources of your server, so you can use it for machine learning projects.</p><p>It can also coexist with Kubernetes. You may even run some of its jobs directly in Kubernetes.</p><p>It has an Enterprise version with some paid features. For example, scaling has just appeared and is implemented through plugins. Both types of horizontal scaling are supported, but vertical scaling is only available in Enterprise version:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9yHTMs5SXep7yP9oKG6ung.jpeg" /></figure><h4>Pros</h4><ul><li>One of the main differences between Nomad and other orchestrators is that it can orchestrate more than just Docker containers. And generally — not containers only. This can be virtual machines, Java binaries, or even Amazon Elastic Container Service.</li><li>Works on all popular operating systems.</li><li>Not demanding resource-wise: about the same as Docker Swarm.</li><li>Low entry level: simple initial setup. To run it, you need to:<br>— Install the Nomad package<br> — Structure the servers: you basically only need to specify the addresses of the machines on which it will run<br> — Start Nomad</li><li>Describing the job, in the driver = “docker” string we start the Docker container and describe some config related to Docker. The beauty of Nomad is that since it can run more than just Docker containers, the job description will not change much. For example, you run some job as systemd.service, or you have a Java app. You describe the job and run it on your server. If at some point you decide to switch to Docker, you will not need to globally rewrite the job. Just replace the driver and change the deploy structure a bit, but the manifest description process will stay the same.</li><li>It supports all of the popular and necessary upgrade strategies described <a href="https://habr.com/ru/companies/kts/articles/591355/#99">at the beginning of this article</a>.</li></ul><h3>Cons</h3><ul><li>Few features out of the box:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-QEfQS3jPDw0zpzfdSKw7Q.jpeg" /></figure><ul><li>There is no load balancing, no autoscaling, no option to add custom controllers.</li><li>The support of the community is a bit better than the Swarm has, but still not much.</li><li>Manifestos are written in the HCL language, which is not common among engineers. If you want to use Nomad, you will have to familiarize yourself with this language:</li></ul><pre>job &quot;{{service_name}}&quot; {<br>  datacenters = [{{list_of_datacenters}}]<br>  <br>  type = &quot;service&quot;<br>  <br>  group &quot;{{service_name}}&quot; {<br>    count = {{count}}<br>    }<br>  task &quot;{{service_name}}&quot; {<br>    driver = &quot;docker&quot;<br>    config {<br>      image = &quot;{{docker_image}}:latest&quot;<br>    port_map = {<br>      http = {{http_port}}<br>    }<br>  }<br>  <br>  service {<br>    name = &quot;{{service_name}}&quot;<br>    port = &quot;http&quot;<br>    }<br>  }<br>}</pre><h3>Kubernetes and OpenShift</h3><p>Kubernetes is an open source project for orchestrating containerized apps.</p><p>OpenShift is a family of containerization software products developed by Red Hat.</p><h4>Architecture and description</h4><p>We review these orchestrators together because OpenShift has Kubernetes “under the hood.”</p><p>Kubernetes is closer to the concepts of framework and technology.</p><p>OpenShift is more of a ready-to-use platform.</p><p>Kubernetes was born within the walls of Google and then transferred to open source. Many large companies use Kubernetes. It works on Linux and Windows.</p><p>OpenShift runs on Red Hat Enterprise Linux exclusively. It only has an Enterprise version with a short trial period. In addition to Kubernetes, it has many other technologies: for code delivery, monitoring, logging, etc.</p><p>There are many ways to install Kubernetes:</p><ul><li>manually, installing Kubernetes binaries on the servers, and dealing with certificate issuance and updates yourself</li><li>passing this on to relatively automated tools, such as kubespray and kubeadm</li><li>use managed solutions</li></ul><p>The ways to install OpenShift also vary greatly, depending on where and how you deploy it.</p><p>Both have utilities letting you try them out. With any of them, you can deploy a full-fledged cluster on your machine and see what Kubernetes or OpenShift are all about:</p><p><strong>Kubernetes</strong>: minikube, kind, k3s</p><pre>$ minikube start --vm-driver-docker</pre><pre>$ kind create cluster</pre><pre>$ k3s server &amp;</pre><p><strong>OpenShift</strong>: minishift</p><pre>$ minishift start</pre><p>Both orchestrators have a complex architecture.</p><p>In Kubernetes, a cluster consists of standard nodes and a Control Plane, which is a master node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XN3HwA-Zz4knYTnqeYSDPQ.jpeg" /></figure><p>Control Plane includes:</p><ul><li><strong>kube-api-server</strong>, that is the central entry point for all Kubernetes components and people who work with the cluster. It provides an API for cluster management.</li><li><strong>kube-controller-manager</strong> manages controllers, such as the node controller, which control a node, or a replica controller, which controls the number of pods deployed in our cluster.</li><li><strong>kube-sheduler</strong> determines when and on which node the pod will run.</li><li><strong>etcd repository</strong> stores the cluster states in key-value format.</li><li><strong>cloud-contoller</strong> is an optional feature. It monitors the controllers of a particular public or private cloud.</li></ul><p>What runs on the nodes:</p><ul><li><strong>kubelet</strong>, which deploys and monitors containers.</li><li><strong>kube-proxy</strong>, which handles the network: it configures the network and network rules so that pods on different nodes could communicate with each other.</li></ul><p>Kubernetes provides a wide range of scalability options.</p><p>With vertical scaling, we can define the request, the amount of resources that will be given to the app at startup, and the limits until which it can expand in digesting resources.</p><p>Tracking the average workload, Kubernetes can monitor replicas and nodes, adding or reducing their number. It works the same way in the cloud, buying or selling nodes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWuUeaTmSGg8eGoadDZ77Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jAMdgvFDrWYh8i0owiKFnA.jpeg" /></figure><p>The minimum working entity of both orchestrators is a pod: a container that can be based on Docker, cri-o, and containerd. But, unlike in Nomad which can orchestrate virtual machines and many other things, it will necessarily be a container.</p><p>There doesn’t have to be only one container in the pod though. There can be several of them, and they will share the network and file system between each other.</p><p>To create a pod, we write a simple YAML file and either apply it or run it directly from the command line. To manage Kubernetes, we use the rather popular kubectl utility.</p><p>Using operators, we can create our entities:<br>PostgreSQL<br>RabbitMQ</p><p>For Postgres, we describe all the necessary parameters. For example, the size of the cluster, the storage, and the databases that will be created for users.</p><p>The table below shows why Kubernetes is the industry standard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P4sbE6A7xjnmp-jFJ1QptQ.jpeg" /></figure><h4>Pros</h4><ul><li>Easy to run in public clouds.</li><li>Out of the box, Kubernetes supports only two update strategies: Rolling and Recreate. But with extensions you can easily add both Blue/Green and Canary.</li><li>Supports Rollback: monitors pod status and health-check. These are commands that can be configured to help Kubernetes better understand what’s going on with the app. In case of problems, it will also roll back to the previous version.</li><li>Kubernetes allows you to describe your manifests in YAML and JSON. YAML is preferred by the majority of users.</li><li>With the Helm batch manager you have a fairly advanced tool for upgrading manifests. You can use loops, string editing, etc.</li><li>Kubernetes has a large number of built-in features. It has everything you need from an orchestrator, and you can constantly expand its capabilities with custom APIs, network plugins, cluster installation and management tools, etc:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aIltqWlAbutGf_mz78-vmg.jpeg" /></figure><ul><li>Kubernetes has a developed community that is very interested in the technology. You can solve almost any problem, or find an engineer who works with Kubernetes.</li><li>The simultaneous pro and con of OpenShift is that the platform is pre-defined for you. On the one hand, you can just take and use it, but, on the other hand, it is not a sure thing that this platform is the best choice for you. You may have to put some other solution side by side with OpenShift and use something here and something there. Therefore, there is a vendor lock-in here: moving from OpenShift to some other orchestrator will be quite a problem.</li><li>Since it is Enterprise, OpenShift has commercial support. Kubernetes does not have it, but it has a large open source community, detailed documentation, and lots of articles and books. Plus, a huge choice of technologies for the user.</li><li>OpenShift offers built-in support for templates.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mp_hrURoDm5QBUH-JrtQ2Q.jpeg" /></figure><h4>Con</h4><p>Both are quite difficult to install on your own.</p><p>How to start using Kubernetes</p><p>There are a few options to get you started:</p><ul><li>Obviously, you just have to start using it.</li><li>Try managed versions from different cloud providers.</li><li>Contact companies that specialize in operating k8s.</li><li>Take specialized learning courses.</li></ul><p>Conclusion: our case</p><p>Obviously, the entry level for Kubernetes or OpenShift is higher than in other solutions. But in the end it is a winning line. When we were choosing an orchestrator, in the end we settled on two options: Kubernetes or Nomad.</p><p>The shortcomings of Docker Swarm were obvious, and it was clear that in the long run it would definitely not work for us. We deploy a large number of apps that are not connected to each other. We need dev, stage, and prod environments, and it’s hard to do with Docker Swarm.</p><p>But we had an existing architecture that didn’t use any of the orchestrators. We used SaltStack to deploy apps to our servers, i.e. we installed them as packages.</p><p>We thought about the easiest way to switch to a different technology. Nomad was very attractive in this respect because it can run certain tasks on the machine. We thought, “Now we’re going to switch the deployment to Nomad, then maybe we’ll start using Docker containers, and then will find some other workaround”.</p><p>But after thinking about it some more, we came to the conclusion that Nomad has a lot of moving parts and a small community. The main reasons why we chose the k8s were:</p><ol><li>A big community.</li><li>Better is included: Kubernetes already has everything you need, and for the most part, you don’t have to look for anything. Of course, you need to get lots of things done in each cluster: to work with TLS certificates, to have a more transparent and convenient deploying, maybe a service mesh. All these things are not built in, but there is a large number of ready solutions.</li></ol><p>Here we should mention the CNCF organization, which promotes container solutions and has an incubator to develop them. One such solution was Kubernetes itself: it was the first project that the CNCF released. After that there were solutions for managing ceph clusters, Ingress Controller, and many more. And it’s very important that there is a tremendous support from the community and the nonprofit organization that manages the development of container technology. There are a lot of companies that contribute to both CNCF and Kubernetes. That’s why we decided it was the best choice.</p><p>The transition was not easy. We had to write a lot of things from scratch and to transfer all the applications into Docker. In about six months we moved all the projects to the new technology. We have been living in Kubernetes ever since. Of course, we have separate servers associated with databases that are deployed separately, but the apps themselves live almost entirely in Kubernetes.</p><p>Share a comment: what orchestrators do you work with? Are there pros and cons that we forgot to mention?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3db33af1e44f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/lonto-digital-services-integrator/kubernetes-and-other-orchestrators-3db33af1e44f">Kubernetes and Other Orchestrators</a> was originally published in <a href="https://medium.com/lonto-digital-services-integrator">Lonto</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>