<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by QuantumSoft on Medium]]></title>
        <description><![CDATA[Stories by QuantumSoft on Medium]]></description>
        <link>https://medium.com/@quantumsoft?source=rss-e0cd69e80f0c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*iDqhmqilX_GvfXeFESFrPA.png</url>
            <title>Stories by QuantumSoft on Medium</title>
            <link>https://medium.com/@quantumsoft?source=rss-e0cd69e80f0c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 13:37:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@quantumsoft/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Chat Application Based on Squid]]></title>
            <link>https://quantumsoft.medium.com/few-words-about-me-8333958d25b3?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/8333958d25b3</guid>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Sun, 07 Apr 2024 17:26:53 GMT</pubDate>
            <atom:updated>2024-04-07T17:30:30.762Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Alexander Belov, senior front-end developer at QuantumSoft</em></p><h3>Few Words About Me</h3><p>Hey! My name is Alex. And today I’ll tell you about Squid Cloud service. Together we’ll explore how <a href="https://squid.cloud/">Squid</a> can help to easily build a real-time chat application using <a href="https://nextjs.org/">Next.js</a> (and <a href="https://react.dev/">React</a>).</p><p>First, let me start with a few words about myself. I’m a well-experienced front-end developer. I worked on many exciting projects, big and small ones. Most of them use Angular or React with REST, JSON RPC, or GraphQL. So these are the technologies, on which I specialize.</p><h3>The Project</h3><p>Now let’s talk about the project. Our task is to build a real-time chat application based on Next.js framework. The application should have a general room, available for everyone. Also, it should have an option to create private rooms with other users. For the backend we will use <a href="https://squid.cloud/">Squid.cloud</a>. As an auth provider, we will use <a href="https://auth0.com/">Auth0</a>. (Squid also supports Cognito and JWT RSA).</p><p>Why Next.js? Just because it’s a very handy and simple framework with a set of features available out of the box. What I personally like about it is that it’s highly structured meaning it’s convenient to work with. The application routes are reflected on the file system; components and services, etc. are placed in corresponding directories — so, you always know where to find things and where to put things.</p><h3>First Steps</h3><p>Assume we have a Next.js project <a href="https://nextjs.org/docs/app/api-reference/create-next-app">created using create-next-app</a>. Also, we’ll need a set of components to build our UI (it can be a 3rd party library, like MUI).</p><p>The next step is to install Auth0 and Squid React SDKs. It’s pretty simple:</p><pre>npm install --save @auth0/auth0-react<br>npm install --save @squidcloud/react</pre><p>We will use <em>Auth0Provider</em> component and <em>useAuth</em> hook from <a href="https://auth0.github.io/auth0-react/">auth0-react</a>. Let’s wrap our application to <em>Auth0Provider</em>.</p><p><em>src/app/layout.tsx:</em></p><pre>... <br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;body&gt;<br>    &lt;Auth0Provider<br>      domain={process.env.NEXT_PUBLIC_AUTH0_DOMAIN}<br>      clientId={process.env.NEXT_PUBLIC_AUTH0_CLIENT_ID}<br>      authorizationParams={{<br>        redirect_uri: process.env.NEXT_PUBLIC_AUTH0_URL_REDIRECT_TO_AFTER_LOGIN,<br>        response_type: &#39;token id_token&#39;,<br>        scope: &#39;openid profile&#39;,<br>      }}<br>      cacheLocation=&quot;localstorage&quot;<br>    &gt;<br>      {children}    <br>    &lt;/AuthProvider&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;<br>...</pre><p><em>NEXT_PUBLIC_AUTH0_DOMAIN</em>, <em>NEXT_PUBLIC_AUTH0_CLIENT_ID</em> values can be taken from Auth0 dashboard. All the environment variables are <a href="https://nextjs.org/docs/pages/building-your-application/configuring/environment-variables">stored in .env.local</a>.</p><p>To make our application interact with Squid, we will create <em>SquidProvider</em> component, which integrates Squid with Auth0.</p><p><em>src/app/components/SquidProvider.tsx:</em></p><pre>import { EnvironmentId, SupportedSquidRegion } from &#39;@squidcloud/common&#39;;<br>import { PropsWithChildren } from &#39;react&#39;;<br>import { SquidContextProvider } from &#39;@squidcloud/react&#39;;<br>import { useAuth0 } from &#39;@auth0/auth0-react&#39;;</pre><pre>export function SquidProvider({<br>  children,<br>}: PropsWithChildren): JSX.Element {<br>  const { user, getAccessTokenSilently } = useAuth0();</pre><pre>  return (<br>    &lt;SquidContextProvider<br>      options={{<br>        appId: process.env.NEXT_PUBLIC_SQUID_APP_ID || &#39;&#39;,<br>        region: (process.env.NEXT_PUBLIC_SQUID_REGION || &#39;&#39;) as SupportedSquidRegion,<br>        environmentId: (process.env.NEXT_PUBLIC_SQUID_ENVIRONMENT_ID || &#39;&#39;) as EnvironmentId,<br>        authProvider: {<br>          integrationId: process.env.NEXT_PUBLIC_SQUID_AUTH_INTEGRATION_ID,<br>          getToken: async () =&gt; user &amp;&amp; (await getAccessTokenSilently()),<br>        },<br>      }}<br>    &gt;<br>      {children}<br>    &lt;/SquidContextProvider&gt;<br>  );<br>}</pre><p><em>NEXT_PUBLIC_SQUID_APP_ID</em>, <em>NEXT_PUBLIC_SQUID_REGION</em>, <em>NEXT_PUBLIC_SQUID_ENVIRONMENT_ID</em> and <em>NEXT_PUBLIC_SQUID_AUTH_INTEGRATION_ID</em> values can be get from Squid dashboard.</p><p>Now let’s also wrap our application to <em>SquidProvider</em>.</p><p><em>src/app/layout.tsx:</em></p><pre>... <br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;body&gt;<br>    &lt;Auth0Provider<br>      ...<br>    &gt;<br>      &lt;SquidProvider&gt;<br>        {children}<br>      &lt;/SquidProvider&gt;<br>    &lt;/AuthProvider&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;<br>...</pre><p>So, we can make the application alive! In other words, now we have an API for creating / login users and we have access to Squid backend functionality, which means we can execute functions and get collections data.</p><h3>Types Reuse</h3><p>It’s nice to have shared types between the backend and the frontend.</p><p>Here is a simple way to organize types reuse. First of all, put all the code into a monorepo. Let’s say the repo has the following structure:</p><pre>squid-chat<br>├── backend<br>│   └── ...<br>└── frontend<br>    └── ...</pre><p>Create <em>package.json</em> file in the repo root directory:</p><pre>{<br>  &quot;name&quot;: &quot;squid-chat&quot;,<br>}</pre><p>Run the following commands to create a workspace for the backend and the frontend:</p><pre>npm init -w backend --yes<br>npm init -w frontend --yes</pre><p>Flag <em>-w </em>points <em>npm init</em> to create a workspace. Flag — yes tells <em>npm init</em> to use default options without prompting a user.</p><p>Run the command to create a workspace for shared code:</p><pre>npm init -w shared --yes</pre><p>Open <em>shared/package.json</em> and change <em>name</em> value:</p><pre>{<br>  &quot;name&quot;: &quot;@squid-chat/shared&quot;<br>  ...<br>}</pre><p>Run the command to be sure that all the modules are installed successfully and workspaces are available:</p><pre>npm install</pre><p>Now we can create <em>shared/types</em> directory and put there all data types definition files and use them in the frontend code the following way:</p><pre>import { User } from &#39;@squid-chat/shared/types/User&#39;;</pre><p>The final package.json should look like this:</p><pre>{<br>  &quot;name&quot;: &quot;squid-chat&quot;,<br>  &quot;workspaces&quot;: [<br>    &quot;shared&quot;,<br>    &quot;frontend&quot;,<br>    &quot;backend&quot;<br>  ]<br>}</pre><p>And here is the final repo structure:</p><pre>squid-chat<br>├── backend<br>│   └── ...<br>├── frontend<br>│   └── ...<br>├── node_modules<br>│   └── ...<br>├── package-lock.json<br>├── package.json<br>└── shared<br>    ├── package.json<br>    └── types<br>        ├── Message.ts<br>        ├── Room.ts<br>        ├── User.ts<br>        ├── UserRoom.ts<br>        └── index.ts</pre><p>Now the frontend part can get the latest types definitions by simple repository pulling. And if some data type is changed, TypeScript compiler will help us quickly find the change and support it.</p><h3>Saving User Info: Document Update and Function Execution</h3><p>In Squid, you can create or change a document directly. If you need to change several documents by one call or you need some complex logic behind the change, we can use executable functions. Let me demonstrate both ways. That’s how we can create a user document:</p><pre>await executeFunction(&#39;createUser&#39;, {<br>  firstName,<br>  lastName<br>});</pre><p>It’s pretty simple, isn’t it?</p><p>That’s how we can update a user presence. It helps understand whether a user is online or not. The code is also pretty simple:</p><pre>await collection&lt;User&gt;(&#39;Users&#39;).doc(id).update({<br>  lastSeen: new Date()<br>});</pre><p>The user document ID here is the Auth0 user ID (sub). Please, see the article about the application’s backend to understand how it works.</p><blockquote><em>Note: In real-life projects, I wouldn’t recommend to pass current date from a client to a backend, just because the date can be wrong or compromised.</em></blockquote><p>Let’s combine this code into a component that allows us to register a new user, get information about a current user, and update this information. Considering “registration” means we know the user’s name.</p><p><em>src/app/components/UserProvider.tsx:</em></p><pre>import {<br>  PropsWithChildren,<br>  createContext,<br>  useCallback,<br>  useContext,<br>  useEffect,<br>  useMemo,<br>  useState,<br>} from &#39;react&#39;;<br>import { useAuth0 } from &#39;@auth0/auth0-react&#39;;<br>import { useSquid } from &#39;@squidcloud/react&#39;;</pre><pre>const PRESENCE_REFRESHING_INTERVAL = 30 * 1000;</pre><pre>type UserContext = {<br>  id: string | null;<br>  isRegistered: boolean;<br>  firstName: string | null;<br>  lastName: string | null;<br>  isOnline: boolean;<br>  timeZone: string | null;</pre><pre>  register({<br>    firstName,<br>    lastName,<br>  }: {<br>    firstName: string;<br>    lastName: string;<br>  }): Promise&lt;void&gt;;</pre><pre>  update({<br>    firstName,<br>    lastName,<br>    timeZone,<br>  }: {<br>    firstName?: string;<br>    lastName?: string;<br>    timeZone?: string;<br>  }): Promise&lt;void&gt;;<br>};</pre><pre>const UserContext = createContext&lt;UserContext | null&gt;(null);</pre><pre>export function UserProvider({<br>  children,<br>}: PropsWithChildren): JSX.Element {<br>  const { isAuthenticated, user } = useAuth0();<br>  const { collection, executeFunction } = useSquid();</pre><pre>  const [id, setId] = useState&lt;string | null&gt;(null);<br>  const [firstName, setFirstName] = useState&lt;string | null&gt;(null);<br>  const [lastName, setLastName] = useState&lt;string | null&gt;(null);<br>  const [timeZone, setTimeZone] = useState&lt;string | null&gt;(null);</pre><pre>  const isRegistered = useMemo(<br>    () =&gt; Boolean(firstName &amp;&amp; lastName),<br>    [firstName, lastName]<br>  );</pre><pre>  const isOnline = useMemo(<br>    () =&gt; Boolean(id) &amp;&amp; isRegistered,<br>    [id, isRegistered]<br>  );</pre><pre>  const register = useCallback(<br>    async ({<br>      firstName,<br>      lastName,<br>    }: {<br>      firstName: string;<br>      lastName: string;<br>    }): Promise&lt;void&gt; =&gt; {<br>      await executeFunction(&#39;createUser&#39;, {<br>        firstName,<br>        lastName,<br>      });</pre><pre>      setFirstName(firstName);<br>      setLastName(lastName);<br>    },<br>    [executeFunction]<br>  );</pre><pre>  const update = useCallback(<br>    async ({<br>      firstName: newFirstName,<br>      lastName: newLastName,<br>      timeZone: newTimeZone,<br>    }: {<br>      firstName?: string;<br>      lastName?: string;<br>      timeZone?: string;<br>    }) =&gt; {<br>      await executeFunction(&#39;updateUser&#39;, {<br>        firstName: newFirstName || firstName,<br>        lastName: newLastName || lastName,<br>        timeZone: newTimeZone || timeZone,<br>      });</pre><pre>      setFirstName(newFirstName || firstName);<br>      setLastName(newLastName || lastName);<br>      setTimeZone(newTimeZone || timeZone);<br>    },<br>    [executeFunction, firstName, lastName, timeZone]<br>  );</pre><pre>  const refreshPresence = useCallback(async () =&gt; {<br>    if (!id) {<br>      return;<br>    }</pre><pre>    await collection(&#39;Users&#39;).doc(id).update({<br>      lastSeen: new Date(),<br>    });<br>  }, [collection, id]);</pre><pre>  useEffect(() =&gt; {<br>    if (!id) {<br>      return;<br>    }</pre><pre>    refreshPresence();</pre><pre>    const presenceRefreshingInterval = setInterval(async () =&gt; {<br>      refreshPresence();<br>    }, PRESENCE_REFRESHING_INTERVAL);</pre><pre>    return () =&gt; {<br>      clearInterval(presenceRefreshingInterval);<br>    };<br>  }, [id, refreshPresence]);</pre><pre>  const userContextValue = useMemo(<br>    () =&gt; ({<br>      id,<br>      isRegistered,<br>      firstName,<br>      lastName,<br>      isOnline,<br>      timeZone,<br>      register,<br>      update,<br>    }),<br>    [<br>      id,<br>      isRegistered,<br>      firstName,<br>      lastName,<br>      isOnline,<br>      timeZone,<br>      register,<br>      update,<br>    ]<br>  );</pre><pre>  return (<br>    &lt;UserContext.Provider value={userContextValue}&gt;<br>      {children}<br>    &lt;/UserContext.Provider&gt;<br>  );<br>}</pre><p>Now we have a component providing a context, which can be used within <a href="https://react.dev/reference/react/useContext"><em>useContext</em></a> hook, so we can work with thecurrent user inside the app. Of course, we need to wrap the app to this component:</p><p><em>src/app/layout.tsx:</em></p><pre>... <br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;body&gt;<br>    &lt;Auth0Provider<br>      ...<br>    &gt;<br>      &lt;SquidProvider&gt;<br>        &lt;UserProvider&gt;<br>          {children}<br>        &lt;/UserProvider&gt;<br>      &lt;/SquidProvider&gt;<br>    &lt;/AuthProvider&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;<br>...</pre><h3>Getting User Info: Simple Collection Document Subscription</h3><p>Okay, we have stored some data in the database. Now we want to get the data. Here is an example how to get the latest snapshot of a user document:</p><pre>const userDocument = await collection(&#39;Users&#39;).doc(userId).snapshot();</pre><p>But what if we want to get the latest snapshot on each document update? For that, Squid gives a fantastic mechanism based on <a href="https://rxjs.dev/">RxJS</a>’s subscriptions — we can just subscribe on snapshots changes of some document. Let’s use this mechanism in our <em>UserProvider</em> to have the current user up to date.</p><p><em>src/app/components/UserProvider.tsx:</em></p><pre>...</pre><pre>import { Subscription } from &#39;rxjs&#39;;</pre><pre>...</pre><pre>export function UserProvider({<br>  children,<br>}: PropsWithChildren): JSX.Element {<br>  const { isAuthenticated, user } = useAuth0();<br>  const { collection, executeFunction } = useSquid();</pre><pre>  const [id, setId] = useState&lt;string | null&gt;(null);<br>  const [firstName, setFirstName] = useState&lt;string | null&gt;(null);<br>  const [lastName, setLastName] = useState&lt;string | null&gt;(null);<br>  const [timeZone, setTimeZone] = useState&lt;string | null&gt;(null);</pre><pre>  ...</pre><pre>  useEffect(() =&gt; {<br>    let userDocumentSubscription: Subscription | undefined;</pre><pre>    setId(null);<br>    setFirstName(null);<br>    setLastName(null);</pre><pre>    const userId = user?.sub;</pre><pre>    if (isAuthenticated &amp;&amp; userId) {<br>      userDocumentSubscription = collection(&#39;Users&#39;)<br>        .doc(userId) <br>        .snapshots()<br>        .subscribe((userDocument) =&gt; {<br>          setId(userId);<br>          setFirstName(userDocument?.data.firstName || null);<br>          setLastName(userDocument?.data.lastName || null);<br>          setTimeZone(<br>            userDocument?.data.timeZone ||<br>              Intl.DateTimeFormat().resolvedOptions().timeZone<br>          );<br>        });<br>    }</pre><pre>    return () =&gt; {<br>      userDocumentSubscription?.unsubscribe();<br>    };<br>  }, [isAuthenticated, user?.sub, collection]);</pre><pre>  ...<br>}</pre><blockquote><em>Note: to avoid memory leaking, don’t forget to call unsubscribe() method of a document subscription in a useEffect cleanup function.</em></blockquote><h3>Getting users, rooms, and messages: queries and joins</h3><p>We have an authentication integrated, we can get and update the data of the current user. The last step is to create a component providing an API for chats. Let’s describe the API:</p><p><em>src/app/components/ChatsProvider.tsx:</em></p><pre>type ChatsContext = {<br>  users: ChatUser[] | null;<br>  roomsByRoomId: Record&lt;string, ChatRoom&gt; | null;</pre><pre>  createChatRoom({<br>    name,<br>    icon,<br>    membersIds,<br>  }: {<br>    name: string;<br>    icon?: string;<br>    membersIds: string[];<br>  }): Promise&lt;ChatRoom&gt;;</pre><pre>  sendTextMessage({<br>    roomId,<br>    message,<br>  }: {<br>    roomId: string;<br>    message: string;<br>  }): Promise&lt;void&gt;;</pre><pre>  sendPollMessage({<br>    roomId,<br>    question,<br>    options,<br>    duration,<br>  }: {<br>    roomId: string;<br>    question: string;<br>    options: string[];<br>    duration: number;<br>  }): Promise&lt;void&gt;;</pre><pre>  resendNotSentMessage(message: NewChatMessage): Promise&lt;void&gt;;</pre><pre>  deleteNotSentMessage(message: NewChatMessage): Promise&lt;void&gt;;</pre><pre>  voteInPoll({<br>    messageId,<br>    optionId,<br>  }: {<br>    messageId: string;<br>    optionId: string;<br>  }): Promise&lt;void&gt;;<br>};</pre><p>Here are the used types:</p><p><em>src/app/components/ChatsProvider.tsx:</em></p><pre>type ChatUser = {<br>  id: string;<br>  firstName: string;<br>  lastName: string;<br>  isOnline: boolean;<br>};</pre><pre>type ChatRoom = {<br>  type: &#39;default&#39; | &#39;breakout&#39;;<br>  id: string;<br>  createdAt: Date;<br>  name: string;<br>  icon?: EmojiPickerEmoji;<br>  members: ChatUser[];<br>  messages: (ChatMessage | NewChatMessage)[];<br>};</pre><pre>export type ChatMessage = {<br>  id: string;<br>  status: ChatMessageStatus.Sent;<br>} &amp; Omit&lt;NewChatTextMessage | NewChatPollMessage&lt;ChatPollOption&gt;, &#39;status&#39;&gt;;</pre><pre>export type NewChatMessage =<br>  | NewChatTextMessage<br>  | NewChatPollMessage&lt;NewChatMessagePollOption&gt;;</pre><pre>export type NewChatTextMessage = {<br>  roomId: string;<br>  type: ChatMessageType.Text;<br>  status: ChatMessageStatus.Pending | ChatMessageStatus.Error;<br>  from: ChatUser;<br>  createdAt: Date;<br>  message: string;<br>};</pre><pre>export type NewChatPollMessage&lt;PollOption = NewChatMessagePollOption&gt; = {<br>  roomId: string;<br>  type: ChatMessageType.Poll;<br>  status: ChatMessageStatus.Pending | ChatMessageStatus.Error;<br>  from: ChatUser;<br>  createdAt: Date;<br>  question: string;<br>  options: PollOption[];<br>  duration: number;<br>};</pre><pre>export enum ChatMessageType {<br>  Text,<br>  Poll,<br>}</pre><pre>export enum ChatMessageStatus {<br>  Pending,<br>  Error,<br>  Sent,<br>}</pre><pre>export type ChatPollOption = {<br>  id: string;<br>  text: string;<br>  votes: string[];<br>};</pre><pre>export type NewChatMessagePollOption = Omit&lt;ChatPollOption, &#39;id&#39;&gt;;</pre><p>There are a lot of types. Only well-defined types make our code safer and more organized.</p><p>Let me explain the code. We need types for a user and a room. A chat room has users and messages. A message can be a text message or a poll, with its options. When a message is not sent, it has no ID. A sent message has “Sent” status. That’s what we described here.</p><p>Now, let’s implement the interface. We’ll start with creating a chat room. Here is the code:</p><p><em>src/app/components/ChatsProvider.tsx:</em></p><pre>...</pre><pre>export function ChatsProvider({ children }: PropsWithChildren): JSX.Element {<br>  const { collection, executeFunction } = useSquid();</pre><pre>  const [users, setUsers] = useState&lt;ChatUser[] | null&gt;(null);<br>  const [roomsByRoomId, setRoomsByRoomId] = useState&lt;Record&lt;string, ChatRoom&gt; | null&gt;(null);</pre><pre>  ...</pre><pre>  const createChatRoom = useCallback(<br>    async ({<br>      name,<br>      icon,<br>      membersIds,<br>    }: {<br>      name: string;<br>      icon?: EmojiPickerEmoji;<br>      membersIds: string[];<br>    }): Promise&lt;ChatRoom&gt; =&gt; {<br>      if (!users) {<br>        throw new Error(&#39;There is no users&#39;);<br>      }</pre><pre>      const createRoomResult = await executeFunction(&#39;createRoom&#39;, {<br>        name,<br>        icon,<br>      });</pre><pre>      const chatRoomId = createRoomResult.__id;</pre><pre>      await executeFunction(&#39;addUsersToChatRoom&#39;, {<br>        roomId: chatRoomId,<br>        userIds: membersIds,<br>      });</pre><pre>      const chatRoomMembers = users.filter((chatUser: ChatUser) =&gt;<br>        membersIds.includes(chatUser.id)<br>      );</pre><pre>      const newChatRoom = {<br>        id: chatRoomId,<br>        type: createRoomResult.type,<br>        createdAt: new Date(createRoomResult.created),<br>        name,<br>        icon,<br>        members: chatRoomMembers,<br>        messages: [],<br>      };</pre><pre>      setRoomsByRoomId((prevRoomsByRoomId) =&gt; ({<br>        ...prevRoomsByRoomId,<br>        [newChatRoom.id]: newChatRoom,<br>      }));</pre><pre>      return newChatRoom;<br>    },<br>    [executeFunction, users]<br>  );</pre><pre>  ...<br> }</pre><p>There’s nothing new here. We create a room by executing <em>createRoom</em> function. Once a room is created, we add users to it (<em>addUsersToChatRoom</em>). Then we store the room to <em>roomsByRoomId</em> state variable. You also may see that <em>users</em> state variable is used, I’ll show you how it becomes set later.</p><p>Let me demonstrate how to send a message in a room.</p><p><em>src/app/components/ChatsProvider.tsx:</em></p><pre>...</pre><pre>export function ChatsProvider({ children }: PropsWithChildren): JSX.Element {<br>  const user = useUser();<br>  const { collection, executeFunction } = useSquid();</pre><pre>  ...</pre><pre>  const [messagesByRoomId, setMessagesByRoomId] = useState&lt;Record&lt;string, ChatMessage[]&gt; | null&gt;(null);<br>  const [notSentMessagesByRoomId, setNotSentMessagesByRoomId] = useState&lt;Record&lt;string, NewChatMessage[]&gt;&gt;({});</pre><pre>  const currentUser: ChatUser | null = useMemo(<br>    () =&gt;<br>      user.id<br>        ? {<br>            id: user.id,<br>            firstName: user.firstName || &#39;&#39;,<br>            lastName: user.lastName || &#39;&#39;,<br>            isOnline: user.isOnline,<br>          }<br>        : null,<br>    [user]<br>  );</pre><pre>  ...</pre><pre>  const sendPollOrTextMessageOptimistically = useCallback(<br>    async ({<br>      roomId,<br>      message = &#39;&#39;,<br>      question,<br>      options,<br>      duration,<br>    }: {<br>      roomId: string;<br>      message?: string;<br>      question?: string;<br>      options?: string[];<br>      duration?: number;<br>    }) =&gt; {<br>      if (!currentUser) {<br>        throw new Error(&#39;There is no current user&#39;);<br>      }</pre><pre>      let newChatMessage: NewChatMessage;</pre><pre>      if (question &amp;&amp; options &amp;&amp; duration) {<br>        newChatMessage = {<br>          roomId,<br>          type: ChatMessageType.Poll,<br>          status: ChatMessageStatus.Pending,<br>          from: currentUser,<br>          createdAt: new Date(),<br>          question,<br>          options: options.map((optionText: string) =&gt; ({<br>            text: optionText,<br>            votes: [],<br>          })),<br>          duration,<br>        };<br>      } else {<br>        newChatMessage = {<br>          roomId,<br>          type: ChatMessageType.Text,<br>          status: ChatMessageStatus.Pending,<br>          from: currentUser,<br>          createdAt: new Date(),<br>          message,<br>        };<br>      }</pre><pre>      setNotSentMessagesByRoomId((prevNotSentMessagesByRoomId) =&gt; {<br>        const newRoomNotSentMessages = [<br>          ...(prevNotSentMessagesByRoomId[roomId] || []),<br>          newChatMessage,<br>        ];</pre><pre>        return {<br>          ...prevNotSentMessagesByRoomId,<br>          [roomId]: newRoomNotSentMessages,<br>        };<br>      });</pre><pre>      try {<br>        const createMessageResult =<br>          await executeFunction&lt;MessagesCollectionDocument&gt;(&#39;createMessage&#39;, {<br>            roomId,<br>            text: message,<br>            pollName: question,<br>            pollOptions: options,<br>            pollDuration: duration,<br>          });</pre><pre>        setNotSentMessagesByRoomId((prevNotSentMessagesByRoomId) =&gt; {<br>          const newRoomNotSentMessages = (prevNotSentMessagesByRoomId[roomId] || []).filter(<br>            (notSentMessage: NewChatMessage) =&gt; notSentMessage !== newChatMessage<br>          );</pre><pre>          return {<br>            ...prevNotSentMessagesByRoomId,<br>            [roomId]: newRoomNotSentMessages,<br>          };<br>        });</pre><pre>        setMessagesByRoomId((prevMessagesByRoomId) =&gt; {<br>          const newChatMessagesByRoomId = { ...prevMessagesByRoomId };</pre><pre>          const newRoomMessage = messageDocumentToChatMessage(createMessageResult);<br>          const newRoomMessages = (newChatMessagesByRoomId[roomId] || []).filter(<br>            (message: ChatMessage) =&gt; message.id !== newRoomMessage.id<br>          );</pre><pre>          newRoomMessages.push({<br>            ...newRoomMessage,<br>            from: newChatMessage.from,<br>          });</pre><pre>          newChatMessagesByRoomId[roomId] = newRoomMessages;</pre><pre>          return newChatMessagesByRoomId;<br>        });<br>      } catch (unknownError) {<br>        newChatMessage.status = ChatMessageStatus.Error;</pre><pre>        setNotSentMessagesByRoomId((prevNotSentMessagesByRoomId) =&gt; {<br>          const newRoomNotSentMessages = (prevNotSentMessagesByRoomId[roomId] || [])<br>            .filter((notSentMessage: NewChatMessage) =&gt; notSentMessage !== newChatMessage)<br>            .concat(newChatMessage);</pre><pre>          return {<br>            ...prevNotSentMessagesByRoomId,<br>            [roomId]: newRoomNotSentMessages,<br>          };<br>        });<br>      }<br>    },<br>    [currentUser, executeFunction]<br>  );</pre><pre>  const sendTextMessage = useCallback(<br>    async ({ roomId, message }: { roomId: string; message: string }) =&gt; {<br>      await sendPollOrTextMessageOptimistically({<br>        roomId,<br>        message,<br>      });<br>    },<br>    [sendPollOrTextMessageOptimistically]<br>  );</pre><pre>  const sendPollMessage = useCallback(<br>    async ({<br>      roomId,<br>      question,<br>      options,<br>      duration,<br>    }: {<br>      roomId: string;<br>      question: string;<br>      options: string[];<br>      duration: number;<br>    }) =&gt; {<br>      await sendPollOrTextMessageOptimistically({<br>        roomId,<br>        question,<br>        options,<br>        duration,<br>      });<br>    },<br>    [sendPollOrTextMessageOptimistically]<br>  );</pre><pre>  ...<br>}</pre><p>Here we have two functions: <em>sendTextMessage</em> and <em>sendPollMessage</em>, both call <em>sendPollOrTextMessageOptimistically</em>. Inside <em>sendPollOrTextMessageOptimistically, </em>we create a new chat message and store it to <em>notSentMessagesByRoomId </em>state variable. Then we try to send the message and if it’s successfully sent, we remove the message from <em>notSentMessagesByRoomId</em> and store it to <em>messagesByRoomId</em>. If the sending failed, we set the message status to <em>Error, </em>remove the message from <em>notSentMessagesByRoomId,</em> and<em> </em>add the message to <em>notSentMessagesByRoomId</em> again, to the end of the room messages array.</p><p>Why do we need <em>notSentMessagesByRoomId</em> state variable? To display messages failed in the UI and to resend them or delete when necessary. Just like this:</p><p><em>src/app/components/ChatsProvider.tsx:</em></p><pre>...<br>export function ChatsProvider({ children }: PropsWithChildren): JSX.Element {<br>  ...</pre><pre>  const [notSentMessagesByRoomId, setNotSentMessagesByRoomId] = useState&lt;Record&lt;string, NewChatMessage[]&gt;&gt;({});<br> <br>  ...</pre><pre>  const deleteNotSentMessage = useCallback(<br>    async (messageToDelete: NewChatMessage) =&gt; {<br>      const { roomId } = messageToDelete;</pre><pre>      setNotSentMessagesByRoomId((prevNotSentMessagesByRoomId) =&gt; {<br>        const newRoomNotSentMessages = (<br>          prevNotSentMessagesByRoomId[roomId] || []<br>        ).filter(<br>          (notSentMessage: NewChatMessage) =&gt; notSentMessage !== messageToDelete<br>        );</pre><pre>        return {<br>          ...prevNotSentMessagesByRoomId,<br>          [roomId]: newRoomNotSentMessages,<br>        };<br>      });<br>    },<br>    []<br>  );</pre><pre>  const resendNotSentMessage = useCallback(<br>    async (messageToResend: NewChatMessage) =&gt; {<br>      deleteNotSentMessage(messageToResend);</pre><pre>      if (messageToResend.type === ChatMessageType.Text) {<br>        await sendTextMessage({<br>          roomId: messageToResend.roomId,<br>          message: messageToResend.message,<br>        });<br>      } else if (messageToResend.type === ChatMessageType.Poll) {<br>        await sendPollMessage({<br>          roomId: messageToResend.roomId,<br>          question: messageToResend.question,<br>          options: messageToResend.options.map(({ text }) =&gt; text),<br>          duration: messageToResend.duration,<br>        });<br>      } else {<br>        throw new Error(<br>          `Unknown message type: &quot;${(messageToResend as any).type}&quot;`<br>        );<br>      }<br>    },<br>    [deleteNotSentMessage, sendTextMessage, sendPollMessage]<br>  );</pre><pre>  ...<br>}</pre><p>We have almost everything for chats but no information about existing users and chat rooms with members and messages. To get this data, we’ll use queries — a mechanism for getting set of documents. Queries also allow us to do some manipulations with data, like filtering, sorting, and so on. Let me demonstrate how it works:</p><p><em>src/app/components/ChatsProvider.tsx:</em></p><pre>import { User as UsersCollectionDocument } from &#39;@squid-chat/shared/types&#39;;</pre><pre>const INACTIVITY_DURATION_TO_CONSIDER_USER_OFFLINE = 45 * 1000;</pre><pre>function userDocumentToChatUser(<br>  userDocument: UsersCollectionDocument<br>): ChatUser {<br>  return {<br>    id: userDocument.__id,<br>    firstName: userDocument.firstName || &#39;&#39;,<br>    lastName: userDocument.lastName || &#39;&#39;,<br>    isOnline: userDocument.lastSeen<br>      ? userDocument.lastSeen.getTime() + INACTIVITY_DURATION_TO_CONSIDER_USER_OFFLINE &gt; Date.now()<br>      : false,<br>  };<br>}</pre><pre>...</pre><pre>export function ChatsProvider({ children }: PropsWithChildren): JSX.Element {<br>  const currentUser = useUser();<br>  const { collection, executeFunction } = useSquid();</pre><pre>  const [users, setUsers] = useState&lt;ChatUser[] | null&gt;(null);</pre><pre>  ...</pre><pre>  useEffect(() =&gt; {<br>    if (!currentUser?.isOnline) {<br>      return;<br>    }</pre><pre>    const usersQuery = collection&lt;UsersCollectionDocument&gt;(&#39;Users&#39;).query();</pre><pre>    const usersQuerySubscription = usersQuery<br>      .sortBy(&#39;firstName&#39;)<br>      .sortBy(&#39;lastName&#39;)<br>      .snapshots()<br>      .subscribe(<br>        (usersDocumentsReferences: DocumentReference&lt;UsersCollectionDocument&gt;[]) =&gt; {<br>          const users: ChatUser[] = usersDocumentsReferences.map(({ data }) =&gt;<br>            userDocumentToChatUser(data)<br>          );</pre><pre>          setUsers(users);<br>        }<br>      );</pre><pre>    return () =&gt; {<br>      usersQuerySubscription.unsubscribe();<br>    };<br>  }, [currentUser?.isOnline, collection]);</pre><pre>  ...<br>}</pre><p>First, we define a function <em>userDocumentToChatUser, </em>which maps a user document from the backend to our <em>ChatUser</em>, considering a user is online if the user’s presence was updated less than 45 seconds ago. Then, inside an effect (that runs only if the current user is authenticated), we query users and sort them by first and last names. Then we just map users’ documents to <em>ChatUser</em> and store the result to <em>users</em> state variable. Again, to avoid memory leaking we call <em>unsubscribe()</em> method in the effect’s clean up function.</p><p>On the backend side, users are stored in <em>Users</em> collection, chat rooms are stored in <em>Rooms</em> collection, members of rooms are presented as <em>UserRoom</em> collection, and messages are in <em>Messages</em>. To query this data combined Squid has the joins feature. Joins are powerful and pretty complicated, so it’s better to take a look at <a href="https://docs.squid.cloud/docs/development-tools/client-sdk/queries/#joining-data-across-collections-and-integrations">the official documentation</a>.</p><p>Let’s modify the effect above to use joined queries for getting chat rooms with members and messages.</p><p><em>src/app/components/ChatsProvider.tsx:</em></p><pre>import { User as UsersCollectionDocument } from &#39;@squid-chat/shared/types&#39;;</pre><pre>...</pre><pre>function roomDocumentToChatRoom(<br>  roomDocument: RoomsCollectionDocument<br>): ChatRoom {<br>  return {<br>    id: roomDocument.__id,<br>    type: roomDocument.type,<br>    name: roomDocument.name,<br>    icon: roomDocument.icon as EmojiPickerEmoji,<br>    createdAt: new Date(roomDocument.created),<br>    members: [],<br>    messages: [],<br>  };<br>}</pre><pre>function messageDocumentToChatMessage(<br>  messageDocument: MessagesCollectionDocument<br>): Omit&lt;ChatMessage, &#39;from&#39;&gt; {<br>  if (&#39;pollName&#39; in messageDocument) {<br>    return {<br>      id: messageDocument.__id,<br>      roomId: messageDocument.roomId,<br>      type: ChatMessageType.Poll,<br>      createdAt: new Date(messageDocument.created),<br>      status: ChatMessageStatus.Sent,<br>      question: messageDocument.pollName || &#39;&#39;,<br>      options: (messageDocument.pollOptions || []).map((optionText: string, index: number) =&gt; ({<br>        id: index,<br>        text: optionText,<br>        votes: messageDocument.pollAnswers?.[index] || [],<br>      })),<br>      duration: messageDocument.pollDuration,<br>    } as Omit&lt;ChatMessage, &#39;from&#39;&gt;;<br>  } else {<br>    return {<br>      id: messageDocument.__id,<br>      roomId: messageDocument.roomId,<br>      type: ChatMessageType.Text,<br>      createdAt: new Date(messageDocument.created),<br>      status: ChatMessageStatus.Sent,<br>      message: messageDocument.text,<br>    } as Omit&lt;ChatMessage, &#39;from&#39;&gt;;<br>  }<br>}</pre><pre>export function ChatsProvider({ children }: PropsWithChildren): JSX.Element {<br>  const currentUser = useUser();<br>  const { collection, executeFunction } = useSquid();</pre><pre>  const [users, setUsers] = useState&lt;ChatUser[] | null&gt;(null);</pre><pre>  const [roomsByRoomId, setRoomsByRoomId] = useState&lt;Record&lt;string, ChatRoom&gt; | null&gt;(null);<br>  const [messagesByRoomId, setMessagesByRoomId] = useState&lt;Record&lt;string, ChatMessage[]&gt; | null&gt;(null);<br>  const [notSentMessagesByRoomId, setNotSentMessagesByRoomId] = useState&lt;Record&lt;string, NewChatMessage[]&gt;&gt;({});</pre><pre>  ...</pre><pre>  useEffect(() =&gt; {<br>    if (!currentUser?.id) {<br>      return;<br>    }</pre><pre>    const usersQuery = collection&lt;UsersCollectionDocument&gt;(&#39;Users&#39;).query();<br>    const roomsQuery = collection&lt;RoomsCollectionDocument&gt;(&#39;Rooms&#39;).query();<br>    const userRoomQuery = collection&lt;UserRoomsCollectionDocument&gt;(&#39;UserRoom&#39;).query();<br>    const messagesQuery = collection&lt;MessagesCollectionDocument&gt;(&#39;Messages&#39;).query();</pre><pre>    const currentUserRoomJoinQuery = collection&lt;UserRoomsCollectionDocument&gt;(&#39;UserRoom&#39;)<br>      .joinQuery(&#39;currentUserRoom&#39;)<br>      .eq(&#39;userId&#39;, currentUser.id);</pre><pre>    const usersQuerySubscription = usersQuery<br>      .sortBy(&#39;firstName&#39;)<br>      .sortBy(&#39;lastName&#39;)<br>      .snapshots()<br>      .subscribe((usersDocumentsReferences: DocumentReference&lt;UsersCollectionDocument&gt;[]) =&gt; {<br>          const users: ChatUser[] = usersDocumentsReferences.map(({ data }) =&gt;<br>            userDocumentToChatUser(data)<br>          );</pre><pre>          setUsers(users);<br>        }<br>      );</pre><pre>    const currentUserRoomRoomsUserRoomUsersJoinQueryBuilder =<br>      currentUserRoomJoinQuery<br>        .join(roomsQuery, &#39;room&#39;, {<br>          left: &#39;roomId&#39;,<br>          right: &#39;__id&#39;,<br>        })<br>        .join(userRoomQuery, &#39;userRoom&#39;, {<br>          left: &#39;__id&#39;,<br>          right: &#39;roomId&#39;,<br>        })<br>        .join(usersQuery, &#39;users&#39;, {<br>          left: &#39;userId&#39;,<br>          right: &#39;__id&#39;,<br>        })<br>        .grouped()<br>        .dereference();</pre><pre>    const currentUserRoomRoomsUserRoomUsersQuerySubscription =<br>      currentUserRoomRoomsUserRoomUsersJoinQueryBuilder<br>        .snapshots()<br>        .subscribe((currentUserRoomRoomsUserRoomUsersQueryResult) =&gt; {<br>          const newRoomsByRoomId =<br>            currentUserRoomRoomsUserRoomUsersQueryResult.reduce(<br>              (<br>                newRoomsByRoomId: Record&lt;string, ChatRoom&gt;,<br>                { room: [{ room: roomDocument, userRoom }] }<br>              ) =&gt; {<br>                const chatRoom = roomDocumentToChatRoom(roomDocument);<br>                const chatRoomMembers = userRoom.map(<br>                  ({ users: [userDocument] }) =&gt; userDocumentToChatUser(userDocument)<br>                );</pre><pre>                newRoomsByRoomId[chatRoom.id] = {<br>                  ...chatRoom,<br>                  members: chatRoomMembers,<br>                };</pre><pre>                return newRoomsByRoomId;<br>              },<br>              {}<br>            );</pre><pre>          setRoomsByRoomId(newRoomsByRoomId);<br>        });</pre><pre>    const currentUserRoomMessagesUserQueryBuilder = currentUserRoomJoinQuery<br>      .join(messagesQuery, &#39;message&#39;, {<br>        left: &#39;roomId&#39;,<br>        right: &#39;roomId&#39;,<br>      })<br>      .limit(MAX_CHAT_MESSAGES_PER_ROOM)<br>      .join(usersQuery, &#39;user&#39;, {<br>        left: &#39;postedByUserId&#39;,<br>        right: &#39;__id&#39;,<br>      })<br>      .grouped()<br>      .dereference();</pre><pre>    const currentUserMessagesQuerySubscription =<br>      currentUserRoomMessagesUserQueryBuilder<br>        .snapshots()<br>        .subscribe((currentUserRoomMessagesUserQueryResult) =&gt; {<br>          const newMessagesByRoomId =<br>            currentUserRoomMessagesUserQueryResult.reduce(<br>              (<br>                newMessagesByRoomId: Record&lt;string, ChatMessage[]&gt;,<br>                { currentUserRoom, message: messages }<br>              ) =&gt; {<br>                const chatRoomMessages = messages.reduce(<br>                  (<br>                    chatRoomMessages: Record&lt;string, ChatMessage&gt;,<br>                    { message, user }<br>                  ) =&gt; {<br>                    if (user[0]) {<br>                      const chatMessage = messageDocumentToChatMessage(message);<br>                      const chatMessageAuthor = userDocumentToChatUser(user[0]);</pre><pre>                      chatRoomMessages[chatMessage.id] = {<br>                        ...chatMessage,<br>                        from: chatMessageAuthor,<br>                      };<br>                    }</pre><pre>                    return chatRoomMessages;<br>                  },<br>                  {}<br>                );</pre><pre>                newMessagesByRoomId[currentUserRoom.roomId] = Object.values(chatRoomMessages);</pre><pre>                return newMessagesByRoomId;<br>              },<br>              {}<br>            );</pre><pre>          setMessagesByRoomId(newMessagesByRoomId);<br>        });</pre><pre>    return () =&gt; {<br>      usersQuerySubscription.unsubscribe();<br>      currentUserRoomRoomsUserRoomUsersQuerySubscription.unsubscribe();<br>      currentUserMessagesQuerySubscription.unsubscribe();<br>    };<br>  }, [currentUser?.id, collection]);</pre><pre>  ...</pre><pre>  const combinedRoomsAndMessagesByRoomId: Record&lt;string, ChatRoom&gt; | null =<br>    useMemo(<br>      () =&gt;<br>        roomsByRoomId &amp;&amp; messagesByRoomId<br>          ? Object.keys(messagesByRoomId).reduce(<br>              (rooms: Record&lt;string, ChatRoom&gt;, roomId: string) =&gt; {<br>                const currentRoom = roomsByRoomId[roomId];</pre><pre>                if (currentRoom) {<br>                  const currentRoomMessages = [<br>                    ...messagesByRoomId[roomId],<br>                    ...(notSentMessagesByRoomId[roomId] || []),<br>                  ].sort(<br>                    (<br>                      chatMessageA: ChatMessage | NewChatMessage,<br>                      chatMessageB: ChatMessage | NewChatMessage<br>                    ) =&gt;<br>                      chatMessageB.createdAt.getTime() -<br>                      chatMessageA.createdAt.getTime()<br>                  );</pre><pre>                  rooms[roomId] = {<br>                    ...currentRoom,<br>                    messages: currentRoomMessages,<br>                  };<br>                }</pre><pre>                return rooms;<br>              },<br>              {}<br>            )<br>          : null,<br>      [roomsByRoomId, messagesByRoomId, notSentMessagesByRoomId]<br>    );</pre><pre>  const chatsContextValue = useMemo(<br>    () =&gt; ({<br>      users,<br>      roomsByRoomId: combinedRoomsAndMessagesByRoomId,<br>      createChatRoom,<br>      sendTextMessage,<br>      sendPollMessage,<br>      resendNotSentMessage,<br>      deleteNotSentMessage,<br>      voteInPoll,<br>    }),<br>    [<br>      users,<br>      combinedRoomsAndMessagesByRoomId,<br>      createChatRoom,<br>      sendTextMessage,<br>      sendPollMessage,<br>      resendNotSentMessage,<br>      deleteNotSentMessage,<br>      voteInPoll,<br>    ]<br>  );</pre><pre>  return (<br>    &lt;ChatsContext.Provider value={chatsContextValue}&gt;<br>      {children}<br>    &lt;/ChatsContext.Provider&gt;<br>  ); <br>}</pre><p>First, we build a query <em>currentUserRoomJoinQuery, </em>which gets all user-room relations where the current user ID is involved. Then we build a query <em>currentUserRoomRoomsUserRoomUsersJoinQueryBuilder, </em>which uses <em>currentUserRoomJoinQuery</em> to get all the data of current user rooms: we have IDs of current user’s rooms — we get the rooms’ info, after that, we get IDs of these rooms members, and then we use these IDs to get info about these members. Then we simply map the result to the application internal types and store the rooms in <em>roomsByRoomId </em>state variable.</p><p>Next, we get messages from each room the current user is a member of (<em>currentUserRoomMessagesUserQueryBuilder</em>), limiting the number of the messages by <em>MAX_CHAT_MESSAGES_PER_ROOM</em>. Also, we get info about each message author. Then we map the data to the internal types and store it in <em>messagesByRoomId</em>.</p><p>We also have <em>combinedRoomsAndMessagesByRoomId</em> cached variable that depends on <em>roomsByRoomId</em>, <em>messagesByRoomId,</em> and <em>notSentMessagesByRoomId</em>. It’s a final step where we combine all the data in one structure, which can be exposed as a value of ChatsContext.</p><p>Since we are done with <em>ChatsProvider,</em> we need to wrap the app to the component:</p><p><em>src/app/layout.tsx:</em></p><pre>... <br>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;body&gt;<br>    &lt;Auth0Provider<br>      ...<br>    &gt;<br>      &lt;SquidProvider&gt;<br>        &lt;UserProvider&gt;<br>          &lt;ChatsProvider&gt;<br>            {children}<br>          &lt;/ChatsProvider&gt;<br>        &lt;/UserProvider&gt;<br>      &lt;/SquidProvider&gt;<br>    &lt;/AuthProvider&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;<br>...</pre><h3>The result. Pros and cons</h3><p>Not taking into account the UI, we have everything to build a chat application! Here it is alive: <a href="https://chat.squid.cloud/">https://chat.squid.cloud</a> (probably you’ll need to allow cross-site tracking in your browser to see the app working). Of course, it’s more complex than some pieces of code I described in this article, but the application is actually based on that code.</p><p>What do I think about Squid? Here are the pros and cons.</p><p>Pros:</p><ol><li>Squid can be used for simple pet projects and big complex applications</li><li>Squid allows to focus on application business logic covering all the infrastructure stuff</li><li>Squid has nice integration with modern frontend frameworks</li><li>Squid API is pretty clean. And Squid team continuously improves the API</li></ol><p>Cons:</p><ol><li>At this moment Squid SDK is not fully documented, there are some caveats</li><li>There are some insignificant mistakes in the documentation</li></ol><p>But I believe the Squid team will handle all these problems shortly.</p><p>And, as a front-end guy, I can say that any more or less experienced front-end developer can become a full-stack person with Squid. Just try it and you‘ll see its power.</p><p><em>The text above was prepared and accomplished by Alexander Belov. The opinions expressed here are the author’s own and do not necessarily represent the views of QuantumSoft.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8333958d25b3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Что значит Stateful Application]]></title>
            <link>https://quantumsoft.medium.com/%D1%87%D1%82%D0%BE-%D0%B7%D0%BD%D0%B0%D1%87%D0%B8%D1%82-stateful-application-4a3ab03461e1?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a3ab03461e1</guid>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Thu, 21 Mar 2024 09:47:06 GMT</pubDate>
            <atom:updated>2024-03-21T09:47:06.284Z</atom:updated>
            <content:encoded><![CDATA[<p>Последнее время все чаще вижу, что многие инженеры не знают или не до конца понимают разницу между stateless и stateful приложениями. В своей статье мне хотелось бы разобраться в этом вопросе.</p><p>Начну с того, что я обнаружил немало неадекватных статей про stateless и stateful приложения. Так, на первой же странице поисковой выдачи по запросу “stateful application” почти все тексты неадекватны. Даже <a href="https://en.wikipedia.org/wiki/State_(computer_science)">статья на Википедии</a> ссылается на отсутствующее определение. Скорее всего, в этом и есть причина укоренившегося неверного представления о разнице между stateless и stateful приложениями.</p><p>В качестве примера неадекватной статьи предлагаю взглянуть на следующую: <a href="https://climstech.com/blog/stateful-and-stateless-applications/">https://climstech.com/blog/stateful-and-stateless-applications/</a></p><p>В тексте сказано: “<em>Stateful Application describes a structure that allows users to </em><strong><em>store, record, and return</em></strong><em> to already established information and processes over the internet.”</em></p><p>По непонятным причинам в качестве примера stateless приложения указан DNS.</p><p>Если предположить, что имеется имеется в виду <strong>протокол</strong> DNS, то это довольно странно, ведь даётся определение stateful/stateless <strong>приложений</strong>, а в качестве примеров используются<strong> протоколы</strong>. Если допустить, что имеются в виду DNS <strong>приложения</strong>, то налицо расхождение с реальностью: DNS сервера<strong> хранят, меняют и отдают </strong>информацию о доменных именах и их связях с IP адресами.</p><p>Я нашёл одну более или менее адекватную <a href="https://appmaster.io/glossary/stateless-application">статью</a>, однако отмечу, что она больше сфокусирована на stateless приложениях.</p><p>Теперь перейдем к сути вопроса. Разница между stateless и stateful приложениями заключается не в том, что они что-то где-то хранят или не хранят, а в <strong>характере </strong>хранимой информации.<strong> Stateful сервер хранит информацию о текущем состоянии (state) клиентского приложения (client).</strong> Обратите внимание, речь идет не о пользовательских данных (например, информация о залогиненном пользователе, тип запроса, данные запроса, и т.п.), но об информации о том, в каком состоянии сейчас клиентское приложение. Не дайте запутать себя! Пользователь (user), пользовательские данные (user data) и состояние клиента (client state) — это разные вещи.</p><p>Давайте уточним, о чем идет речь:</p><p>User — человек (или скрипт), взаимодействующий с системой.</p><p>User data — набор значений программных сущностей приложения. Это может быть тип запроса, значения параметров запроса, значения, связанные с этими параметрами, и т.п.</p><p>Client state — <a href="https://en.wikipedia.org/wiki/State_(computer_science)#:~:text=2N.-,Program%20state,-%5Bedit%5D">состояние</a> клиентского приложения в клиент-серверной системе.</p><p>Чтобы разъяснить не совсем однозначное определение user data и client state, давайте рассмотрим следующий пример. Клиент-серверное приложение использует пользовательские сессии для авторизации пользователя и определения того, что нужно пользователю. Зачастую информация о сессии хранится где-то в базе данных на стороне сервера, а клиент хранит идентификатор сессии и с каждым запросом его передаёт. Можно запустить другое клиентское приложение и использовать ранее сохранённый идентификатор сессии для дальнейшей работы с сервером. Если сервер не увидит разницы, это означает, что у вас, скорее всего, stateless приложение, а не stateful. В этом примере сессия будят являться пользовательскими данными (user data), а не состоянием клиента (client state). Сервер хранит не информацию о состоянии клиента (client state), а пользовательскую информацию (user data), которую можно так или иначе передать между клиентами.</p><p>Разберем еще одно неудачное представление. Довольно часто в статьях заявляется, что stateful приложение зависит от предыдущих запросов (или транзакций — названия разнятся). Это более или менее верно в определённых случаях, но наличие/отсутствие предыдущих запросов не является фактором, определяющим stateful приложение. Не важно, каким путём было достигнуто текущее состояние клиента. Важно только то, что оно <strong>хранится и используется</strong> сервером. Здесь приведу вам простой пример stateful приложения, где нет ни одного запроса от клиента (после установления TCP соединения), — это сервер рассылки каких-либо одинаковых сообщений всем клиентам. В данном случае состоянием клиента, хранящимся на сервере, будет факт того, что клиент ожидает от сервера данных. Впрочем, надо отметить, что это частый случай, когда факт того, что клиент ожидает от сервера данных, хранится и используется сервером.</p><p>На мой взгляд, самый важный вывод из того, является ли приложение stateful или stateless, — это оценка сложности имплементации автоматического горизонтального масштабирования. Stateful приложение, как правило, сложно масштабировать горизонтально и тем более — автоматически. По своему опыту не могу назвать ни одного достаточно обобщённого (generic) решения, которое позволит легко масштабировать любое stateful приложение. В то время как stateless приложение, как правило, достаточно легко масштабируется. Есть готовое решение, которое подойдёт для всех stateless приложений, — балансировщик входящих запросов между запускаемыми серверами приложений. Тут сложность будет в основном в том, чтобы правильно подобрать уже существующие компоненты, из которых система будет собираться.</p><p>Не могу пройти мимо еще одного важного, на мой взгляд, аспекта. Следует понимать, что “диагноз” stateful или stateless зависит от точки зрения — уровня абстракции, с которого рассматривается приложение. Например, ВСЕ web-приложения ведут себя как stateful (даже если они могут быть названы stateless) в определённые моменты времени — в момент передачи данных по установленному TCP соединению.</p><p>Также замечу, что использование stateful протокола (TCP, например) не обязательно приводит к тому, что приложение будет stateful. Определение зависит от уровня абстракции, с которого мы смотрим на приложение, и от архитектуры с деталями имплементации. Верно и обратное — использование stateless протокола (UDP, например) не гарантирует, что приложение будет stateless. Повторю, это зависит от деталей реализации и точки зрения.</p><p>Имеет смысл упомянуть, что HTTP протокол тоже является stateful, но есть нюанс. Если в приложении будут использованы только GET/POST/PUT/etc., то протокол можно вполне охарактеризовать как stateless, кроме того без особых проблем получится создать stateless приложение. Но как только в приложении начинают использоваться WebSocket’ы, мы имеем дело со stateful протоколом и попытка создать stateless приложение оказывается сильно затруднена. Отдельно упомяну long polling — создание stateless приложения может оказаться довольно простым или непростым. Тут снова определение будет зависеть от уровня абстракции, с которого мы оцениваем приложение, и деталей реализации.</p><p>То же справедливо и для приложений — часть функционала, предоставляемого системой, может быть stateless, а часть — stateful.</p><p>Порой не удаётся сходу определить, каким является приложение — stateless или stateful. В таком случае… не надо определять вовсе. Главная ценность диагноза — лёгкость определения того, насколько сложно будет горизонтально масштабировать такое приложение. Другими словами, можно сэкономить время разработки, не тратя его на неверные решения. Если не удаётся легко определить характер приложения — поздравляю, вам попалась сложная система и придётся искать решение, как будто это stateful приложение.</p><p>Также не стоит думать, что <a href="https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/">StatefulSet</a> предназначен исключительно для stateful приложений. Kubernetes даёт чёткое определение его назначению. А название… ну, какое выбрали.</p><p>Ну и немного личного. Порой встречаются совершенно неадекватные заявления типа “<a href="https://glossary.cncf.io/stateful-apps/">Any kind of online shop that remembers your cart is a stateful app</a>”. Это не так. По наличию/отсутствию корзины нельзя определить, является ли приложение stateless или stateful. Нужно смотреть на детали имплементации.</p><p>Напоследок предложу идею конвертации stateful приложения в stateless. Можно попробовать преобразовать состояние клиента (client state) в пользовательские данные (user data), чтобы ими можно было свободно обмениваться между запущенными инстансами серверного ПО. Если это удалось сделать,то большую часть работы можно считать сделанной.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a3ab03461e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My experience with Squid]]></title>
            <link>https://quantumsoft.medium.com/my-experience-with-squid-1db16c1f20ca?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/1db16c1f20ca</guid>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 09:56:17 GMT</pubDate>
            <atom:updated>2024-01-31T09:56:17.993Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Oleg Tarasov, JS Full Stack Developer at QuantumSoft</em></p><p>I recently had an opportunity to dive into the Squid.cloud. In this article, I would like to tell about my journey with Squid, from my initial impressions through the process and up to successful integration with a ChatRoom project. Additionally, I will share my thoughts about <strong>pros and cons of Squid and highlight the projects where it shines the brightes</strong>t.</p><p>By leveraging my experience and expertise, combined with the power of Squid,<strong> I aim to provide valuable insights and recommendations for developers looking to optimize their backend development workflow. So, let’s get started!</strong></p><h4>About me and my background</h4><p>Before we delve into Squid, let me introduce myself — I am a JS Full Stack developer. With over 5 years of commercial experience, I have worked on a wide range of projects, specializing in Node.js with Typescript and the Nest.js framework on the backend, and React, Angular, and Vue on the frontend. I was excited to explore Squid and see how it could enhance my development process and simplify backend tasks.</p><h4>What is Squid</h4><p>As a programmer, you’re likely familiar with the challenges of setting up and managing backend infrastructure for your applications. This is where Squid comes in and makes your life easier. Squid is a serverless middle-tier platform designed to simplify backend development and accelerate the delivery of projects.</p><p>At its core, Squid aims to replace the traditional backend setup by providing a unified platform that handles the complexities of connecting databases, APIs, and backend services to any frontend in a secure and scalable manner. With Squid, you can focus on building the frontend and delivering a seamless user experience, without getting bogged down by backend infrastructure management.</p><blockquote>One of the key advantages of Squid is its ability to eliminate the need for complex backend configurations. It offers out-of-the-box integrations with popular databases like MongoDB, MySQL, CockroachDB, and PostgreSQL</blockquote><p>Squid also provides <strong>seamless integration with Auth0</strong>, a widely-used authentication and authorization service. This makes it easy to implement robust user authentication and access control mechanisms, ensuring the security of your application without having to reinvent the wheel.</p><blockquote>Another powerful feature of Squid is its support of <strong>server-side executables</strong>. With Squid, you can execute server-side functions that require access to secrets, perform queries not authorized for the current user. This gives you the flexibility to implement business logic, without compromising security or scalability.</blockquote><p>Squid offers robust security. It provides access control, allowing you to define security rules that control access to different entities such as databases, backend functions, and APIs.</p><p>In the following sections, I will tell about my experience with Squid, discussing its implementation in a ChatRoom application and highlighting strengths and weaknesses of using Squid in different project scenarios.</p><h3>What I was going to build</h3><p>I decided to build a ChatRoom application. Here are the key features and requirements:</p><p>• Real-time messaging</p><p>• User authentication and authorization</p><p>• User, Rooms create/read/update/delete</p><p>• Scalability</p><p>If I were to develop a backend without relying on Squid, I would opt for combination of Nest.js, WebSockets, Docker, Nginx and a reliable database. However, with Squid, all these additional components become unnecessary.</p><h4>Squid implementation</h4><p>Here’s an overview of how Squid was integrated into the project:</p><p>1. Squid setup: The first step was to set up Squid by creating a Squid Cloud account. This provided access to the Squid dashboard, where I could configure the necessary resources and settings for the application.</p><p>2. Database integration: Squid offers seamless integration with popular databases like MongoDB, MySQL, CockroachDB, and PostgreSQL. I preferred to stay with default DB. I created five schemas and defined schema fields with types.</p><p>Schemas: <em>Users, Rooms, UserRoom, Messages, Presence.<br></em> Here’s an example of my Users schema:</p><p><strong>You can access db queries in React directly, I connected Squid to React.</strong></p><pre>export function SquidProvider({ children }: { children: React.ReactNode }): JSX.Element {<br>  return (<br> &lt;SquidContextProvider<br>   options={{<br>     appId: process.env.NEXT_PUBLIC_SQUID_APP_ID,<br>    region: (process.env.NEXT_PUBLIC_SQUID_REGION,<br>     environmentId: process.env.NEXT_PUBLIC_SQUID_ENVIRONMENT_ID<br>   }}<br> &gt;<br>   {children}<br> &lt;/SquidContextProvider&gt;<br>  );<br>}</pre><p><strong>And subscribe to get Users</strong></p><pre>const usersQuerySubscription = collection(&#39;Users&#39;).query()<br>  .sortBy(&#39;firstName&#39;)<br>  .sortBy(&#39;lastName&#39;)<br>  .snapshots()<br>  .subscribe(usersDocuments =&gt; {<br> const users = usersDocuments.map(({ data }) =&gt; userDocumentToChatUser(data));<br> setUsers(users);<br>  });</pre><p><strong>Or complex query to get messages with joined user in room in real-time!</strong></p><pre>const currentUserRoomQuery = collection(&#39;UserRoom&#39;)<br>  .joinQuery(&#39;userRoom&#39;).eq(&#39;userId&#39;, currentUser.id);<br>const messagesQuery = collection(&#39;Messages&#39;).query().limit(50);<br>const userQuery = collection(&#39;Users&#39;).query();<br> <br>const currentUserRoomMessagesUserQueryBuilder = currentUserRoomQuery<br>  .join(messagesQuery, &#39;message&#39;, {<br> left: &#39;roomId&#39;,<br> right: &#39;roomId&#39;<br>  })<br>  .join(userQuery, &#39;user&#39;, {<br> left: &#39;postedByUserId&#39;,<br> right: &#39;__id&#39;<br>  })<br>  .grouped()<br>  .dereference();</pre><h4><strong>Auth0 Integration</strong></h4><p>I configured necessary settings in Squid to authenticate users using Auth0, ensuring that only authorized users could access the chatroom, and read messages only in rooms where they are exist.[ММ1]</p><p>On the frontend, the top-level Auth0 initialization code looks like this.</p><p>We added SquidInitializer</p><pre>&lt;SquidContextProvider<br>   options={{<br>     appId: process.env.NEXT_PUBLIC_SQUID_APP_ID,<br>     region: process.env.NEXT_PUBLIC_SQUID_REGION,<br>     environmentId: process.env.NEXT_PUBLIC_SQUID_ENVIRONMENT_ID,<br>   }}<br> &gt;<br>   &lt;SquidInitializer&gt;<br>     {children}<br>   &lt;/SquidInitializer&gt;<br> &lt;/SquidContextProvider&gt;<br> <br> <br> <br> <br>export function SquidInitializer({ children }) {<br>  const { idToken } = useAuth();<br>  const { setAuthIdToken } = useSquid();<br>  useEffect(() =&gt; {<br> setAuthIdToken(idToken || undefined, process.env.NEXT_PUBLIC_SQUID_AUTH_INTEGRATION_ID);<br>  }, [idToken, setAuthIdToken]);<br> <br>  return &lt;Fragment&gt;{children}&lt;/Fragment&gt;;<br>}</pre><p>The set <strong>AuthIdToken</strong> function is called [ММ2] with the <strong>idToken</strong>. This associates the authentication token with the Squid integration, allowing Squid to handle authentication and authorization for the whole application.</p><p>And you can check that user is authenticated:</p><pre>return this.isAuthenticated();</pre><p>Or get current user:</p><pre>const auth = this.getUserAuth();<br>const collection = this.squid.collection(&#39;Users&#39;)<br>const user = await collection.doc(auth?.userId).snapshot()</pre><h4>Executables</h4><p>Squid server-side executables provided a convenient way to options as create user, create room, update profile, add user to chat room. I will give you an example of the simplest one and the most complex one below.</p><pre>@executable()<br>async createRoom({ name, icon }) {<br> const userId = this.getUserAuth()?.userId;<br> <br> if (userId) {<br>   const roomsCollection = this.squid.collection(&#39;Rooms&#39;)<br> <br>   const doc = await roomsCollection.doc()<br> <br>   await doc.insert({<br>     created: new Date(),<br>     name: name,<br>     icon: icon,<br>     ownerId: userId,<br>     type: &#39;breakout&#39;<br>   })<br>   return doc.data<br> }<br>}<br> <br> <br>@executable()<br>async addUsersToChatRoom({ userIds, roomId }): Promise&lt;void&gt; {<br> if (userIds?.length &gt; 0 &amp;&amp; roomId) {<br> <br>   const currentUserId = this.getUserAuth()?.userId<br>   const room = await this.squid.collection&lt;Room&gt;(&#39;Rooms&#39;).doc(roomId).snapshot()<br> <br>   if (currentUserId &amp;&amp; room &amp;&amp; room.data.ownerId === currentUserId) {<br> <br>     const userRooms = await this.squid<br>            .collection(&quot;userRoom&quot;)<br>            .query()<br>            .eq(&quot;roomId&quot;, roomId)<br>            .in(&quot;userId&quot;, userIds)<br>            .snapshot();<br> <br>     if (userRooms?.length === 0) {<br>          const userRoomCollection = this.squid.collection(&#39;UserRoom&#39;)<br> <br>          await Promise.all(userIds.map((userId) =&gt; {<br>            return userRoomCollection.doc().insert({<br>              userId,<br>              roomId<br>            })<br>          }))<br>     }<br>   }<br> }<br>}<br> <br>const createRoomResult = await executeFunction(&#39;createRoom&#39;, {<br>  name,<br>  icon,<br>});</pre><h3>Security rules</h3><p>Squid security rules feature played a crucial role in enforcing access restrictions within the application. I utilized Squid’s security rules to define granular access controls for the database collections and specific data within them.</p><p>For example:</p><ul><li>Restricting access to the Rooms collection to allow read access to the Rooms collection only for authenticated users. This ensured that only users who were logged in and authenticated could view the list of available chat rooms</li></ul><pre> <br>@secureCollection(&#39;Rooms&#39;, &#39;read&#39;)<br>secureRoomsRead(): boolean {<br>  return this.isAuthenticated();</pre><p>• To provide more complex access control, I leveraged Squid security rules to allow read access to specific messages only to users who were members of the chat room. This ensured that users could only access and view messages that were relevant to the chat rooms they were part of.</p><pre> <br>@secureCollection(&#39;Messages&#39;, &#39;read&#39;)<br>async secureMessageRead(context): Promise&lt;boolean&gt; {<br>  const userId = this.getUserAuth()?.userId<br> <br>  if (userId) {<br> const roomIdConditions = context.getConditionsForField(&#39;roomId&#39;);<br> const inRoomIdCondition = roomIdConditions.find((c) =&gt; c.operator === &quot;in&quot;);<br> const roomIds = inRoomIdCondition?.value;<br> <br> if (!roomIds?.length) {<br>   return false;<br> }<br> const userRooms = await this.squid<br>     .collection(&quot;UserRoom&quot;)<br>     .query()<br>     .in(&quot;roomId&quot;, roomIds)<br>     .eq(&quot;userId&quot;, userId)<br>     .snapshot();<br> return userRooms.length === roomIds.length;<br>  }<br>  return false<br>}</pre><h3>Overview. Pros and cons</h3><p>After working with Squid and implementing it in my ChatRoom project, I can confidently say that Squid is a powerful and efficient tool for backend development. Here are the key results and my observations:</p><h4>Pros of Squid:</h4><p>• Simplified Backend Development: Squid eliminates the need for complex backend setups and configurations. Developers can easily connect databases, APIs, and backend services to any frontend in a secure and scalable way.</p><p>• Rapid Development: Squid significantly speeds up the development process by providing ready-to-use integrations like database and authentication. This allows to focus more on building the core features of the application rather than spending time on infrastructure setup.</p><p>• Scalability and Security: Squid offers scalability and security tools such as Auth0, and security rules.</p><p>• Deployment in Squid is designed to be straightforward and out-of-the-box. Squid provides a serverless middle-tier platform that handles the deployment and scaling of your application’s backend resources automatically. This means that you don’t need to worry about provisioning and managing servers or configuring scaling settings.</p><h4>Cons of Squid:</h4><p>• Learning Curve: While Squid simplifies backend development, there is still a learning curve involved in understanding its concepts and how to use its features most efficiently. Developers who are new to Squid may need some time to familiarize themselves with its documentation and best practices.</p><ul><li>Limited Customization: Squid provides a set of predefined integrations and functionalities, which may limit the level of customization you can achieve. If your project requires highly specific or unique backend requirements, Squid may not be the best fit.</li></ul><h4>Projects where Squid shines the brightest:</h4><p>• Rapid Prototyping: Squid is an excellent choice for rapid prototyping or MVP development.</p><p>• Small to Medium-sized Applications: Squid is well-suited for small to medium-sized applications where speed of development and scalability are crucial. It provides a solid foundation for building backend functionality without the need for extensive infrastructure setup.</p><p>• Real-time Applications: Squid’s support for real-time messaging and its executable functions make it a great choice for building real-time applications like chatrooms, collaborative tools, or live streaming platforms.</p><p><em>The text above was prepared and accomplished by Oleg Tarasov. The opinions expressed here are the author’s own and do not necessarily represent the views of QuantumSoft.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1db16c1f20ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom DatePicker with modified slots]]></title>
            <link>https://quantumsoft.medium.com/custom-datepicker-with-modified-slots-517dbb014118?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/517dbb014118</guid>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Fri, 19 Jan 2024 09:58:46 GMT</pubDate>
            <atom:updated>2024-01-22T09:17:10.325Z</atom:updated>
            <content:encoded><![CDATA[<p><em>By Yuriy Axenov, Senior Frontend Developer ar QuantumSoft</em></p><p><em>For better convenience and comprehension of the further text, you can first have a look at the code in GitHub repository by clicking here: </em><a href="https://github.com/yuriy-axenov-qs-pro/medium-mui-datepicker"><em>github repository with code</em></a></p><p>This is a common scenario where all elements in a project should consistently function and appear in a specific style. The MUI framework provides a variety of capabilities to fulfill such requirements. In this article, we will explore methods for customizing components as a whole and address a non-trivial situation involving the DatePicker component. To illustrate this, we will implement a single-page application where the distinction between the standard display and the modified version will be evident.</p><p>We will use <a href="https://vitejs.dev/guide/">Vite</a>, as it is a simple and lightweight solution for launching React applications.</p><pre>yarn create vite app --template react-ts</pre><p>Let’s configure aliases for the src folder in project.</p><pre>yarn add -D @types/node</pre><p>vite.config.ts</p><pre>...<br>alias: {<br>      &#39;@&#39;: path.resolve(__dirname, &#39;./src&#39;),<br>},<br>...</pre><p>tsconfig.json</p><pre>... <br>&quot;paths&quot;: {&quot;@/*&quot;: [&quot;./src/*&quot;] },<br>...</pre><p>We will use the Sass preprocessor for working with styles.</p><pre>yarn add -D sass</pre><p>Let’s install all the necessary dependencies for working with MUI and the MUI DatePicker component.</p><pre>yarn add @mui/material @emotion/react @emotion/styled<br>yarn add @mui/x-date-pickers<br>yarn add dayjs</pre><p>The next step is to set up a <a href="https://mui.com/material-ui/customization/theming/">theme</a>, which is one of the options for customizing components in MUI.</p><p>I would like the colors used in the theme to be accessible in CSS files when needed, so let’s add them as CSS variables and then use them in the theme object. To achieve this, we’ll implement a scheme with variables.module + variables files, allowing us to obtain values in JavaScript code and simultaneously set these values in :root.</p><p>variables.module.scss</p><pre>...<br>:export {<br>    primary_color: $primary-color;<br>    secondary_color: $secondary-color;<br>    accent_color: $accent-color;<br>    ...<br>}</pre><p>variables.scss</p><pre>@use &#39;./variables.module&#39; as *;<br>:root {<br>    --primary-color: #{$primary-color};<br>    --secondary-color: #{$secondary-color};<br>    --accent-color: #{$accent-color};<br>    ...<br>}</pre><p>In our simple example, we will focus solely on modifying the color scheme. However, MUI provides the flexibility to customize a wide variety of parameters by configuring the theme. This practical approach allows you to tailor your application to a designer’s specified style without having to make direct changes to the components themselves. Therefore, it is advisable to explore this approach before considering creating your own customizations. In your case, working with the theme may fulfill all your requirements.</p><pre>const theme = createTheme({<br>    palette: {<br>        primary: {<br>            main: variables.primary_color,<br>        },<br>        secondary: {<br>            main: variables.secondary_color,<br>        },<br>        info: {<br>            main: variables.info_color,<br>        },<br>        warning: {<br>            main: variables.accent_color,<br>        },<br>        background: {<br>            default: variables.background_color,<br>        },<br>        error: {<br>            main: variables.error_color,<br>        },<br>        text: {<br>            primary: variables.text_color,<br>            secondary: variables.secondary_text_color,<br>        },<br>    },</pre><p>The theme object itself is not enough for the theme to take effect. Therefore, let’s make some changes to the main.tsx file. If you only want to apply the theme to specific pages, you can use the ThemeProvider on those particular pages where you want it to take effect. In our case, we will apply the theme to the entire application.</p><p>main.tsx</p><pre>...<br> &lt;ThemeProvider theme={theme}&gt;<br>      &lt;CssBaseline /&gt;<br>      &lt;App /&gt;<br> &lt;/ThemeProvider&gt;<br>...</pre><p>It’s time to write our first components. As a first step, let’s write a styled Input. In reality, we’ll just change the padding, but that’s enough to understand how it works.</p><p>Input.tsx</p><pre>import MuiInput from &#39;@mui/material/Input&#39;;<br>import { styled } from &#39;@mui/material/styles&#39;;<br><br>const Input = styled(MuiInput)`<br>  &amp; .MuiInput-input {<br>    padding: 10px 12px;<br>  }<br>`;<br><br>export default Input;</pre><p>MUI provides us with the ability to write CSS code inside a JS file through the @emotion/styled library. When modifying styles for standard MUI components, it’s important to understand which class we want to alter. To find out the classes associated with a component you can refer to the MUI <a href="https://mui.com/material-ui/api/input/#classes">documentation</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/446/1*uE_gD9RF8nzR5r-fNn4Utg.png" /></figure><p>The DatePicker component looks similar to the TextField component before interacting with it. To clearly see that we are using the modified TextField component, we will need to implement it first.</p><p>In practice, TextField is a complex component composed of various elements. While modifying the theme or CSS properties with Emotion is a great option, let’s consider a scenario where we want to utilize our new Input.tsx within a styled TextField. In this case, we would need to manually recreate the structure of the original TextField. Although the structure in this example may not match the original MUI TextField component exactly, we will cover the main elements.</p><p>The structure of the our TextField.</p><pre>&lt;FormControl&gt;<br>  &lt;InputLabel&gt;...&lt;/...&gt;<br>  &lt;Input /&gt;<br>&lt;/...&gt;</pre><p><a href="https://mui.com/material-ui/api/form-control/">FormControl</a> is the root element in the structure tree and is responsible for defining how the TextField will appear.</p><p>InputLabel is responsible for rendering the label of the field.</p><p>Input is the component where actual input values will be entered, and we have already created it.</p><pre>const TextFieldRoot = styled(FormControl)`<br>    &amp; .MuiInputBase-root {<br>      background-color: var(--input-bg-color);<br>      border: 1px solid var(--input-border-color);<br>      border-radius: 2px;<br>      box-sizing: border-box;<br>  <br>      ${(props) =&gt;<br>    props.error &amp;&amp;<br>    `<br>        --input-border-color: var(--error-color);<br>        --input-border-color-hover: var(--error-color);<br>        --primary-color: var(--error-color);<br>      `}<br>  <br>      &amp;:hover:not(.Mui-disabled) {<br>        border-color: var(--input-border-color-hover);<br>      }<br>  <br>      &amp;:focus-within:not(.Mui-disabled) {<br>        background-color: unset;<br>        border-color: var(--primary-color);<br>      }<br>    }<br>  <br>    &amp; .MuiInputBase-root.MuiInputBase-adornedStart {<br>      .MuiInputBase-input {<br>        padding-left: 0;<br>      }<br>    }<br>  <br>    &amp; .MuiInputBase-root.MuiInputBase-adornedEnd {<br>      .MuiInputBase-input {<br>        padding-right: 0;<br>      }<br>    }<br>  <br>    &amp; .MuiInputAdornment-positionStart {<br>      padding-left: 12px;<br>    }<br>  <br>    &amp; .MuiInputAdornment-positionEnd {<br>      padding-right: 12px;<br>    }<br>  <br>    &amp; .MuiInput-root .MuiSelect-icon {<br>      right: 4px;<br>    }<br>  `;</pre><p>We’re customizing the appearance of our component by adjusting colors and padding for different states. When rewriting styles, it’s important to note that theme values won’t be applied automatically unless we reference them directly. In the example, I use CSS variables matching theme values. However, MUI <a href="https://mui.com/system/styled/#using-the-theme">allows</a> direct access to theme values for better component flexibility.</p><pre>interface TextFieldProps extends InputProps {<br>  label?: React.ReactNode;<br>  containerRef?: React.Ref&lt;HTMLDivElement&gt;;<br>}<br><br>const TextField: React.FC&lt;TextFieldProps&gt; = forwardRef((props, inputRef) =&gt; {<br>  const id = useId();<br>  const { containerRef, ...rest } = props;<br>  return (&lt;TextFieldRoot<br>    variant=&quot;standard&quot;<br>  &gt;<br>    {props.label &amp;&amp; (<br>      &lt;InputLabel id={`label-${id}`} shrink htmlFor={id}&gt;<br>        {props.label}<br>      &lt;/InputLabel&gt;<br>    )}<br>    &lt;Input<br>      {...rest}<br>      disableUnderline<br>      id={id}<br>      inputRef={inputRef}<br>      ref={containerRef}<br>    /&gt;<br>  &lt;/TextFieldRoot&gt;);<br>});</pre><p>Now the visual difference is apparent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*RFhBEQ5d2lxBQY1lxSTevA.png" /></figure><p>The preparation is complete, and now we can start working with the DatePicker component itself.</p><p>To begin, let’s display the standard DatePicker without any modifications. It’s important to note that we are using the dayjs library for date manipulation, so we need to explicitly use the dayjs adapter through the LocalizationProvider.</p><pre>&lt;LocalizationProvider dateAdapter={AdapterDayjs}&gt;<br>  &lt;Box sx={{ width: &#39;250px&#39; }}&gt;<br>    &lt;DatePicker label=&quot;Label&quot; /&gt;<br>  &lt;/Box&gt;<br>&lt;/LocalizationProvider&gt;</pre><p>Our next objective is to display a DatePicker component that utilizes our customized TextField.</p><p>To achieve this, we will take advantage of the recently added slots mechanism in MUI, which allows us to modify the default behavior and appearance of components. The slots parameter is available for most complex components in MUI, including the DatePicker. By referring to the <a href="https://mui.com/x/api/date-pickers/date-picker/#slots">documentation</a>, we can explore the available slots for the component and gain a better understanding of the purpose of each specific slot.</p><p>After analyzing the documentation, one of these two options is likely to be suitable for us.</p><p>textField — form control with an input to render the<br>value inside the default field.</p><p>field — component used to enter the date with the keyboard.</p><p>It seems that the field slot is the most suitable for achieving our goal. However, the textField slot could also work for our purposes, making everything straightforward.</p><p>Let’s try to modify the DatePicker using the textField slot. We encounter a type mismatch error right away. The reason is that our version of TextField actually has much more limited functionality than the original TextField and uses completely different props (based on InputProps rather than TextFieldProps). But let&#39;s assume that we want to use the component we already have. This is a good example if we want to use TextField that we wrote entirely on our own or a TextField built on another library. In such a case, we would have to use a more low-level slot—field.</p><p>But here too, we face a type mismatch. In this case, we need to understand what the field slot expects and write a wrapper that conforms to the expected props.</p><p>It expects a type that extends UseDateFieldProps and BaseSingleInputFieldProps. Let&#39;s declare the interface and write the wrapper accordingly.</p><pre>interface DateFieldWrapperProps<br>    extends UseDateFieldProps&lt;Dayjs&gt;,<br>    BaseSingleInputFieldProps&lt;Dayjs | null, <br>      Dayjs, <br>      FieldSection, <br>      DateValidationError&gt; { }<br><br>const DateFieldWrapper: React.FC&lt;DateFieldWrapperProps&gt; = (props) =&gt; {<br>    const { <br>       inputRef: externalInputRef,<br>       slots,<br>       slotProps,<br>       ...textFieldProps } = props;<br><br>    const response = useDateField&lt;Dayjs, typeof textFieldProps&gt;({<br>        props: textFieldProps,<br>        inputRef: externalInputRef,<br>    });<br>    const {<br>        // get rid of non available props for our Input<br>        onClear,<br>        clearable,<br>        focused,<br><br>        InputProps,<br>        ref,<br>        ...others } = response;<br><br>    return &lt;STextField<br>        containerRef={InputProps?.ref}<br>        startAdornment={InputProps?.startAdornment}<br>        endAdornment={InputProps?.endAdornment}<br>        {...others}<br>        ref={ref}<br>    /&gt;;<br>}</pre><p>Implementing the wrapper is a straightforward process. We just need to handle the incoming data from the DatePicker, as we would with standard MUI components. MUI already provides the useDateFieldhook specifically for this purpose. By utilizing the responsevariable obtained from this hook, we receive a set of parameters that are ready to be passed to any of our components that will occupy the fieldslot.</p><p>It can be said that we have solved our task; now we just need to specify the wrapper as the field slot for the DatePicker.</p><pre>const DatePicker: React.FC&lt;DatePickerProps&lt;Dayjs&gt;&gt; = (props) =&gt; {<br>    return (<br>        &lt;MuiDatePicker<br>            {...props}<br>            slots={{<br>                field: DateFieldWrapper,<br>                ...props.slots,<br>            }}<br>        /&gt;);<br>}</pre><p>However, we need to understand what InputProps, ref, and why we are not passing whole response.</p><p>You can read more about ref in the official React documentation. In short, ref itself can represent any value. However, in our case, it is references to HTML elements that constitute the component. So, having this reference, the internal code can access this HTML element and do something with it, such as obtaining its coordinates on the screen.</p><p>InputProps represents the parameters specifically for the Input component. It&#39;s important to understand that the Input component consists not only of the &lt;input&gt; tag but is a tree of HTML elements where the &lt;input&gt; tag is nested within a parent container. This is why we specify ref from InputProps in containerRef so that the DatePicker can communicate with the container containing the &lt;input&gt;. However, DatePicker also uses access to the &lt;input&gt; tag—in our case, this is handled by the ref prop. Since we used forwardRef when creating the TextField, the value specified in ref will be available as the second parameter in the forwardRef function.</p><p>Let’s take a look on TextField compoment code.</p><pre> &lt;Input<br>      {...rest}<br>      disableUnderline<br>      id={id}<br>      inputRef={inputRef}<br>      ref={containerRef}<br>    /&gt;</pre><p>The inputRef variable corresponds to the variable name used in forwardRef, which will hold the value we passed to ref in the wrapper. Similarly, the containerRef variable is a prop we are using for the TextField, so it has the same name as we used in the wrapper.</p><p>The inputRef prop in Input is for the reference to the &lt;input&gt; tag, so we assign it the ref from response by passing the inputRef variable. Since Input is the container, its ref should be associated with containerRef.</p><p>The most challenging part is now complete. We have also removed the onClear, clearable, and focused parameters, as our TextField does not support them. If needed, we can implement them separately, but they are not included in this example. The startAdornment and endAdornment properties are nested within the InputProps object, so we need to pass them separately.</p><p>Now, let’s examine the result. As you can see, the styled version utilizes the wrapper and showcases our customized TextField, successfully achieving our desired outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*VnsJQLIiFtMGZvTHXUOmqg.png" /></figure><ol><li><a href="https://react.dev/reference/react">React API</a></li><li><a href="https://mui.com/">Material UI</a></li><li><a href="https://vitejs.dev/">Vite</a></li><li><a href="https://mui.com/material-ui/api/input/">MUI Input</a></li><li><a href="https://mui.com/material-ui/react-text-field/">MUI TextField</a></li><li><a href="https://mui.com/x/react-date-pickers/date-picker/">MUI DatePicker</a></li><li><a href="https://github.com/yuriy-axenov-qs-pro/medium-mui-datepicker">Github Repository with project code</a></li></ol><p><em>The text above was prepared and accomplished by Yuriy Axenov. The opinions expressed here are the author’s own and do not necessarily represent the views of QuantumSoft.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=517dbb014118" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Minimizing Downtime during EBS Encryption in Kubernetes]]></title>
            <link>https://quantumsoft.medium.com/minimizing-downtime-during-ebs-encryption-in-kubernetes-0085b516ea8c?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/0085b516ea8c</guid>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Sun, 31 Dec 2023 10:00:53 GMT</pubDate>
            <atom:updated>2024-01-18T09:42:12.131Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*fYO9GCnz3TB7oIsw6PQwcw.png" /></figure><p>In an era of increasing focus on data security and strict confidentiality requirements, encrypting disk storage in cloud environments, such as Amazon EBS (Elastic Block Store), is not just a recommendation but a necessity.</p><p>However, a challenge arises when existing EBS volumes in a Kubernetes environment are not initially encrypted. Administrators and engineers face the task of implementing encryption for these volumes, which is associated with the risk of temporary downtime and loss of service availability. This problem is particularly acute for systems where even short-term downtimes are unacceptable, as any interruption can have serious consequences.</p><blockquote>In this article, we will focus on methods and strategies for encrypting EBS for StatefulSet in Kubernetes, minimizing or eliminating downtimes.</blockquote><h3>Encrypting EBS for StatefulSet with Nginx in Kubernetes</h3><h4>Scenario Overview</h4><p>For our example, we will take a StatefulSet that manages several instances of Nginx. These instances use EBS in AWS for data storage. Our goal is to implement encryption for these EBS volumes without causing downtime in the operation of Nginx.</p><p><strong><em>Step 1: Launching StatefulSet with Nginx</em></strong></p><p>To begin with, we will create a StatefulSet that will manage several instances of Nginx. Here we assume that you have already configured a Kubernetes cluster and have access to its API via kubectl.</p><p>Create the following nginx-statefulset.yaml manifest:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/362/1*c1g8pDeXbIn0dqTYyF6mBw.png" /></figure><p>Launch the StatefulSet using the command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/1*GDqcAbw3hiKUuP3Y6e5hCA.png" /></figure><p><strong><em>Step 2: Checking Encryption of PVC</em></strong></p><p>Now that we have the PVC, it is necessary to check that it is not encrypted. To do this, first look at the StorageClass used by the PVC. Use the command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*WFSnoc6BYPzJvJLqm7xGzw.png" /></figure><p>Replace <strong><em>`nginx-storage-0`</em> </strong>with the name of your PVC. This command will return the name of the StorageClass used by the PVC.</p><p>Next, check if this StorageClass supports encryption. Usually, this can be done by looking at the StorageClass documentation or its manifest. In AWS EKS, EBS-level encryption can be enabled in the StorageClass parameters.</p><p><strong><em>Step 3: Creating an Encrypted Storage Class</em></strong></p><p>To encrypt EBS in Kubernetes, you need to create a Storage Class that will use a KMS (Key Management Service) key for encryption. This will ensure that all new volumes created under this Storage Class will be automatically encrypted.</p><h4>Creating a KMS Key</h4><p>Before creating the Storage Class, make sure you have a KMS key that you want to use for encryption. If you don’t have a key yet, it can be created in the AWS Management Console or using AWS CLI.</p><h4>Encrypted Storage Class Manifest</h4><p>Create a manifest for the Storage Class with the KMS key specified. Below is an example of the manifest:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*9YlSHVZyOoVJvYMA0VQH1g.png" /></figure><p>Replace <strong><em>`&lt;region&gt;`</em></strong>, <strong><em>`&lt;account-id&gt;</em></strong><em>`</em>, and <strong><em>`&lt;key-id&gt;`</em></strong> with the appropriate values of your KMS key.</p><h4>Applying the Manifest</h4><p>Apply the manifest using kubectl:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*1JXIX8ObMja0JHOywY-U8A.png" /></figure><p>Now that the Storage Class has been created, it can be used to create encrypted EBS volumes. All PVCs that are created using this Storage Class will automatically be encrypted using the specified KMS key.</p><p>Important Points</p><p>- Ensure that you have the necessary access rights to use the KMS key in Kubernetes.<br>- Check if your version of Kubernetes supports EBS encryption using KMS.<br>- After creating encrypted EBS volumes, you can proceed to migrate data from existing PVCs to the new encrypted volumes, which will be described in the following steps of the article.</p><p><strong><em>Step 4: Creating VolumeSnapshotClass</em></strong></p><p>To create snapshots of your current EBS volumes, it’s necessary to set up a VolumeSnapshotClass. This will enable taking snapshots of the volume states, which can then be used to create encrypted copies of EBS. We will use the instructions provided on the GitHub page of AWS EBS CSI Driver — <a href="https://github.com/kubernetes-sigs/aws-ebs-csi-driver/tree/master">https://github.com/kubernetes-sigs/aws-ebs-csi-driver/tree/master</a></p><p><strong><em>Step 5: Saving the StatefulSet Manifest</em></strong></p><p>Before beginning the encryption procedure, it’s essential to save the current StatefulSet manifest for possible recovery or debugging. To do this, use the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/360/1*A7m_AzlaK1Y6zr4iEmyMYg.png" /></figure><p>Replace <strong><em>`[stsname]` </em></strong>with the name of your StatefulSet.</p><p><strong><em>Step 6: Deleting StatefulSet Without Removing Pods</em></strong></p><p>To delete the StatefulSet while keeping the pods running, use the command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/340/1*MatpDrak0rkQMsd9oKaoXA.png" /></figure><p>This will preserve the current state of the pods and prevent their automatic deletion.</p><p><strong><em>Step 7: Deleting a Single Pod</em></strong></p><p>Next, manually delete one of the pods to free up the PVC associated with it. This can be done using the command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*M5cKaqnXwXrpwY33SNtbeA.png" /></figure><p>Replace <strong><em>`[podname]`</em></strong> with the name of the pod you want to delete.</p><p><strong><em>Step 8: Recreating PVC Using the New Storage Class</em></strong></p><p>Now, recreate the PVC using the new encrypted Storage Class. For this, you can use a script that automates this process. Here is an example of such a script:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/822/1*Zf-_faVBv3bzBfIEJ-G1Dg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*qafuDkh-lKRY_uYfrtpiOg.png" /></figure><p>Save this script to a file and execute it, passing the name of the PVC that needs to be recreated. This script will create a snapshot of the current PVC, delete the original PVC, and create a new PVC using the created snapshot and the encrypted Storage Class.</p><p><strong><em>Step 9: Restoring StatefulSet</em></strong></p><p>After you have recreated the PVC for one of the pods, the next step will be to restore the original StatefulSet. This will allow Kubernetes to manage the pods and ensure their correct operation. Use the previously saved StatefulSet manifest for this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*i3Ud58A2Vu0M_vMClMKW-w.png" /></figure><p>This command will restore the StatefulSet with its original configuration. Kubernetes will automatically connect the new encrypted PVCs to the corresponding pods.</p><p><strong><em>Step 10: Repeating the Process for the Remaining Pods</em></strong></p><p>Now, it is necessary to repeat steps 5 to 9 for each remaining pod in the StatefulSet. This process includes:</p><p>Repeat this process for each pod in the StatefulSet until all PVCs have been transitioned to use encrypted EBS volumes. This method minimizes downtimes and ensures a safe migration to encrypted data storage.</p><blockquote>Thus, this approach ensures data encryption for StatefulSet in Kubernetes with minimal downtimes, which is critically important for maintaining continuous operation of applications and services.</blockquote><p>Nikolay Jusev<br>QuantumSoft</p><p><em>The guide above was prepared and accomplished by Nikolay Jusev. The opinions expressed here are the author’s own and do not necessarily represent the views of QuantumSoft.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0085b516ea8c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software application interior design]]></title>
            <link>https://quantumsoft.medium.com/software-application-interior-design-a5e23e810e2d?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5e23e810e2d</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ddd]]></category>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Mon, 19 Sep 2022 10:06:08 GMT</pubDate>
            <atom:updated>2022-09-29T13:49:47.143Z</atom:updated>
            <content:encoded><![CDATA[<p><em>“Space, light and order. Those are the things that men need just as much as they need bread or a place to sleep.”</em></p><p><em>Le Corbusier</em></p><p>At the beginning of a project, the question always comes up: “How do we structure the project?” Should we follow the default package structuring pattern offered by the framework or choose anything else? I need to point out that I use the term “package” because, from my point of view, it is a clearer term to describe an independent part of a program that can be easily moved from one place to another, taken out for reuse or deleted altogether.</p><p>To understand the task scope, we need to outline two extremes. On the one hand, we have an option with no structure at all, as if we are trying to write the whole program in one file; on the other hand, we have an overcomplicated, deeply nested structure with each class in a separate package. As you can guess, the best possible option is somewhere in the middle. But what does it look like and what principles should we stick to when managing the project? Keep reading!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuMbzmRtKEjkXlCFGXx8cw.jpeg" /></figure><p><strong>Turnkey apartment</strong></p><p>Most frameworks like ASP.NET, Spring, Ruby on Rails, or Django offer the Model-View-Controller MVC [1] pattern as a standard for project organization. But why do they offer this approach? Is it the best option and in what cases? We need to go back to the origins to answer these questions and to understand why this pattern is used.</p><p>The MVC pattern was first described by Trygve Reenskaug in 1978. It is easy to understand. You can use it to solve the following tasks due to the layered architecture:</p><ul><li>code splitting,</li><li>code reuse,</li><li>creating different representations for the same model.</li></ul><p>This pattern is suitable for client-server applications, although it was originally designed for desktop applications. Since then, other patterns have been added to the category of structural patterns, such as:</p><ul><li>Presentation–abstraction–control (PAC) 1987</li><li>Model-View-Presenter (MVP) 1990</li><li>Entity-Boundary-Interactor (EBI) 1992</li><li>Presentation Model 2004</li><li>Model-View-ViewModel (MVVM) 2005</li><li>Resource-Method-Representation (RMR) 2008</li><li>Models-Operations-Views-Events (MOVE) 2012</li><li>Action-Domain-Responder (ADR) 2014</li></ul><p>Some patterns are more suitable for client-server applications, because they better match the HTTP request/response cycle, while others are less suitable for this. If you look at the timeline, you may notice that the “first mover advantage” is fundamental to making the MVC approach appear in most frameworks as the default pattern. Now, let’s try to answer the question: is this really the best option for structuring a project?</p><p>In small projects, package organization is not critical, but all successful projects tend to grow. However, in projects with a large codebase, especially if you’re creating a monolithic application, it makes a big difference. Developers are frequently tasked with finding the code snippet responsible for a certain function. Since at the start of the project the default pattern is usually chosen, let’s take a look at an example of such a project at the initial stage.</p><p>At the first nesting level, we already have at least three packages. It will likely be necessary to create the Repositories package for the data access layer. You will also need the Services package for reusing common parts of the user’s business scripts. As a result, we end up with the following structure:</p><p><em>MyCompanyNameProject</em></p><ul><li>models</li><li>views</li><li>controllers</li><li>services</li><li>repositories</li></ul><p>It has become popular recently to create web applications using the web service + REST API + SPA client bundle. This means that the backend is not responsible for the representation of our resulting application, but only provides a tool to retrieve and modify data, for example using the REST API. Therefore, the Views package is deleted and replaced by the Dtos package with Data Transfer Objects — classes describing the REST API method contract. Different frameworks may use different terminology, and the term “entities” may be used instead of “models” and “resources” — instead of “controllers” in some cases.</p><p>Now, imagine that you have just joined a project, and your task is to expand the existing functionality. For example, add user notifications. To do this, you need to localize the part of the program that is responsible for it and figure out what is already done and what needs to be added. Looking at the structure from the example above, we can’t say anything about the features of our program and in which package the part of the code responsible for notifying users is located. We can only use global search and intuition or go from package to package and read the names of nested packages and classes. Also, if the project becomes large, there will probably be a couple of dozen packages at the first nesting level, and each package will have dozens or maybe even hundreds of classes.</p><p>In simple cases, this folder structure works well, but as the project grows, navigating and understanding it becomes problematic. This approach is suggested only because the framework cannot anticipate specific features of your project and offer you a more sophisticated structure. This responsibility lies entirely with the developers.</p><p><strong>The arm’s length principle</strong></p><p>Imagine that you have bought an apartment, and you are free to plan its room layout. When you are planning your apartment furnishings, you easily find a place for the dishwasher, sink and dish dryer. The building’s architect has already thought this through and ran pipes to the part of the apartment where the kitchen is supposed to be. In this case, we follow the rule: the sink, dryer, and other things are used in the same context.</p><p>When structuring a project, it is also better to stick to contextual coherence rather than linguistic similarity. Surely, you don’t want to put a washing machine and a sewing machine next to each other. For the same reason, you should not put all controllers in the same folder, just because the name of the classes ends with the same word.</p><p>Another factor that matters is covering similar user scenarios with an individual package without the need to use other packages. In our example, the kitchen is a separate package. The kitchen is responsible for several user scenarios, such as:</p><ul><li>cooking,</li><li>dishwashing,</li><li>food storage.</li></ul><p>They are all closely related and require the use of items that are similar in purpose. We need a spoon for cooking and eating, and we have to wash it afterwards and keep it somewhere handy. Sometimes, we may need a chair from the study if we have more guests than we expected, but that doesn’t mean we should combine the study and the kitchen. The same applies to development.</p><p>We also have plumbing, wiring and heating in the house — these are the most important things if you want to live in comfort. These utilities are designed first, the work on them is thoroughly planned, as they run through the entire house and changing these systems in the future after construction is completed results in certain difficulties and costs. In the house, we rarely move a tap or an outlet or add a new one. In programming, on the other hand, it happens constantly during every new sprint. This is called a <em>cross-cutting</em> concern. Often, you can implement it using an individual package and add it to other packages by means of the aspect-oriented programming. You can decorate methods and classes to add cross-cutting concerns very quickly without messing up the logic of the underlying code by using a declarative approach.</p><p><strong>DDD interior</strong></p><p>First, let’s formulate the key principles of a well-structured project:</p><ul><li>The functionality you need is easy to find in it.</li><li>Packages of the same level are consistent with each other.</li><li>Packages are loosely coupled to each other.</li><li>There is high cohesion inside the package.</li></ul><p>There are several concepts in DDD that directly affect the project structure. Bounded contexts are among these concepts. They reflect the global division of the product into separate, highly autonomous subsystems. It would be reasonable to reflect this at the first nesting level. For example, in our apartment project, it could be kitchen, bedroom, living room, bathroom, and so on.</p><p>At the second level of nesting, the division is related to the technical aspect of program development. Inspired by DDD, we would like to have a pure kernel with encapsulated business logic in it. So, let’s allocate a separate “domain” package for this. We will use it to collect all our aggregates, their events, business services, and interface definitions for accessing and storing aggregates. In addition, we always need a layer through which our users can interact with the domain, while ensuring transactionality, competitive access and authorization rules. Let’s add the “application” package for this purpose. The main purpose of this package is to coordinate the interaction of infrastructure items and delegate the execution of requests to the domain. These APIs can use various transport communication protocols to receive requests from the outside world. We run into something similar when implementing a data access layer. We’ll put all the technical stuff into a separate “infrastructure” package.</p><p>Let’s dive deeper and try to understand what is inside each previously defined package. At the third level of nesting in the “domain” package, there should be packages with names clear even to non-programmers. These packages often reflect the division of the domain into features. For this, we will need to use ubiquitous language terms. There is a list of rules for package design in Vaughn Vernon’s book, but packages are called modules there.</p><p>As an example, let’s use software development as a service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*he_f5hiFAZ87rFytCX5vRw.png" /></figure><p>The basic rule when diving in is that names change from more general to more specific. Going through each level, we see that the packages are consistent with each other. The first level reflects the global division of the product, the second — technical division in order to emphasize the domain, the third — division by features. As a result, you can select what you need easier and faster. If you need to reuse, move or delete a package, as little effort as possible will be required, since this structure ensures low coupling between packages and high cohesion within them.</p><p>It is also worth keeping an eye on the dependencies between packages. If packages are properly organized, the domain package should not depend on other packages. The dependencies between the packages within a single bounded context are as follows.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*0JI-WYnYaE2YZ_q_3a8tjw.png" /></figure><p><strong>Moving in</strong></p><p>At the end, I would like to point out that programmers develop programs for other programmers. And the processor does not care what our packages, classes and variables are called. That is why we should rely more on psychology and human perception, rather than on the popularity of a particular pattern for architecture structuring. We can structure a project in order to optimize the time needed for the programmer’s daily tasks. This approach has a number of advantages, which we have described, but it also has disadvantages. As we know, naming is one of the hardest programming tasks. In practice, this can be solved by applying Event Storming to jointly develop a ubiquitous language and a domain area model.</p><p><em>By Michael Lazko, Senior Backend Developer at QuantumSoft</em></p><ol><li><a href="https://www.martinfowler.com/eaaDev/uiArchs.html">Martin Fowler — GUI Architectures</a></li><li><a href="http://www.rusdoc.ru/articles/18358/">http://www.rusdoc.ru/articles/18358/</a></li><li><a href="https://docs.microsoft.com/ru-ru/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/ddd-oriented-microservice">https://docs.microsoft.com/ru-ru/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/ddd-oriented-microservice</a></li><li><a href="http://aspiringcraftsman.com/2007/08/25/interactive-application-architecture/">http://aspiringcraftsman.com/2007/08/25/interactive-application-architecture/</a></li><li><a href="https://www.amazon.com/Implementing-Domain-Driven-Design-Vaughn-Vernon/dp/0321834577">Vaughn Vernon Implementing-Domain-Driven-Design</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5e23e810e2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[QuantumSoft Project Portfolio]]></title>
            <link>https://quantumsoft.medium.com/quantumsoft-project-portfolio-599da35c3c8d?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/599da35c3c8d</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[projects]]></category>
            <category><![CDATA[portfolio]]></category>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Mon, 10 Jan 2022 17:56:51 GMT</pubDate>
            <atom:updated>2022-01-10T18:03:03.876Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_YZHd1pTPTBLpNgCPNGZA.png" /></figure><h3>Tablet app for ECG simulator</h3><p><strong>Client: </strong>Realityworks provides comprehensive learning solutions that use hands-on aids, student activities, and assessment tools to create innovative learning environments.</p><p><strong>Challenge</strong>: Realityworks asked us to develop an app that would connect a tablet to the hardware of an ECG simulator via USB.</p><p><strong>Results</strong>: The app comes installed on a tablet as part of the <a href="https://www.realityworks.com/product/ecg-simulator/">ECG simulator package</a>. QuantumSoft maintains the application.</p><p><a href="https://quantumsoft.medium.com/building-an-app-wired-with-ecg-simulator-539c75ec957d">Read the full story about the project here!</a></p><p><strong>Tools</strong>: Xamarin.Forms</p><blockquote><strong>References</strong>:<br><a href="https://www.realityworks.com/blog/this-award-winning-simulator-teaches-ecg-lead-placement-and-reading/">This award-winning simulator teaches ECG lead placement and reading</a></blockquote><blockquote><a href="https://www.realityworks.com/blog/realityworks-ecg-simulator-wins-2020-edison-award/">Realityworks® ECG Simulator Wins 2020 Edison Award</a></blockquote><blockquote><a href="https://www.youtube.com/watch?v=Au0i6V4M_9k">YouTube demonstration video</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnFnV7sCZyWumOZOKiNAYA.png" /></figure><h3>Tablet app for auscultation simulator</h3><p><strong>Client</strong>: <a href="https://www.realityworks.com/">Realityworks</a> provides comprehensive learning solutions that use hands-on aids, student activities, and assessment tools to create innovative learning environments.</p><p><strong>Challenge</strong>: The application had to control an auscultation simulator via BLE.</p><p><strong>Results</strong>: The app comes installed on a tablet as part of the <a href="https://www.realityworks.com/product/auscultation-trainer/">Auscultation Trainer package</a>.</p><p><strong>Tools</strong>: Xamarin.Forms</p><blockquote><strong>References</strong>:<br><a href="https://www.realityworks.com/blog/customize-auscultation-practice-with-realityworks-new-auscultation-trainer/">Customize auscultation practice with Realityworks’ new Auscultation Trainer</a></blockquote><blockquote><a href="https://www.realityworks.com/blog/realityworks-ecg-simulator-wins-2020-edison-award/">Realityworks® ECG Simulator Wins 2020 Edison Award</a></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObFLJU8I4iPUJM067ZF2Nw.png" /></figure><h3>Apps for various devices to access entertainment database</h3><p><strong>Client</strong>: <a href="https://minnowtv.com/">Minnow Stream Inc.</a> provides a huge database with detailed information about nearly any movie, TV show or series ever produced.</p><p><strong>Challenge</strong>: Minnow needed a powerful backend to process data and provide it quickly at a user’s request. <br>The company also wanted apps on all popular mobile and TV platforms.</p><p><strong>Results</strong>: Minnow TV is up and running, with our collection of client apps: <a href="https://play.google.com/store/apps/details?id=com.minnowapp.minnow.android.mobile&amp;hl=ru&amp;gl=US">Android</a>, <a href="https://play.google.com/store/apps/details?id=com.minnowapp.minnow.android.tv&amp;hl=ru&amp;gl=US">Android TV</a>, <a href="https://apps.apple.com/us/app/minnow-watch-shows-and-movies/id1451099084#?platform=iphone">iPhone</a>, <a href="https://apps.apple.com/us/app/minnow-watch-shows-and-movies/id1451099084#?platform=ipad">iPad</a>, <a href="https://apps.apple.com/us/app/minnow-watch-shows-and-movies/id1451099084#?platform=appleTV">Apple TV</a>, <a href="https://www.amazon.com/Minnow-Watch-Shows-and-Movies/dp/B0818RBD21">Amazon Fire TV</a>. QuantumSoft maintains and continues to develop the platform’s apps.</p><p><strong>Tools</strong>: C#, .NET Core</p><blockquote><strong>References</strong>:<br><a href="https://www.prnewswire.com/news-releases/next-gen-streaming-video-guide-minnow-makes-splashy-debut-300956082.html">Next Gen Streaming Video Guide “Minnow” Makes Splashy Debut</a> — Cision PR Newswire</blockquote><blockquote><a href="https://advanced-television.com/2019/11/12/streaming-guide-minnow-goes-live/">Streaming guide Minnow goes live</a> — Advanced Television</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjIE6Xv2mHL5YmUywGRQ_Q.png" /></figure><h3>Self-service kiosk and mobile app for food ordering</h3><p><strong>Client</strong>: <a href="https://www.getrevi.com/">Revi</a> is a digital marketing and branding company in San Francisco, California.</p><p><strong>Challenge: </strong>Revi wanted help expanding an online service for ordering food. The client had already begun the kiosk, with the backend on Django and frontend on Vue.js, <br>as well as a back-office app for Android, built on NativeScript.</p><p><strong>Results</strong>: QuantumSoft created the <a href="https://apps.apple.com/sr/app/get-revi/id1518287410">iPhone</a> app, which we maintain and will continue to develop. We’ll also help Revi develop other apps.</p><p><strong>Tools</strong>: Python/Django, Vue Native, MySQL, TypeScript/JavaScript, Swift, Kotlin</p><blockquote><strong>References</strong>:<br><a href="https://www.prnewswire.com/news-releases/revi-emerges-from-stealth-raises-2m-seed-round-to-help-restaurants-deliver-fast-personalized-and-safe-in-person-and-online-experiences-while-increasing-revenues-301194910.html">Revi Emerges from Stealth, Raises $2M Seed Round to Help Restaurants Deliver Fast, Personalized, and Safe In-Person and Online Experiences While Increasing Revenues</a> — Cision PR Newswire</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AJ1opo8engjEiXkepA38w.png" /></figure><h3>GDPR-compliant data storage for WordPress forms</h3><p><strong>Client</strong>: <a href="https://fortressdb.com/">FortressDB</a> is a startup offering data storage to clients within their GDPR-registered country of business.</p><p><strong>Challenge: </strong>FortressDB wanted to allow users of WordPress websites to store data in the same region where they conducted business.</p><p><strong>Results</strong>: QuantumSoft built a service with cloud storage based in the client’s country of business and a WordPress plugin that provided the website configuration and exchanged data with the cloud.</p><p><strong>Tools</strong>: Backend — Node.js, Express, PostgreSQL<br>Plugin — React, PHP</p><blockquote><strong>References</strong>:<br><a href="https://pod.co/tools-are-tools/rich-hill-fortressdb">Podcast</a> with the project creator — Tools are Tools</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1pnMcevbjLPYPQclebkJEg.png" /></figure><h3>Service for automated document creation and completion</h3><p><strong>Client</strong>: Based in San Francisco, <a href="https://www.docasaurus.com/">Docasaurus</a> helps specialists who need to repeatedly fill out standard document sets.</p><p><strong>Challenge: </strong>Docasaurus wanted a service that could upload various legal documents to a system and complete them automatically, <br>based on set rules and taking relevant client details into account.</p><p><strong>Results</strong>: QuantumSoft built a streamlined online service to automate document completion and enriched it with handy functionality.</p><p><strong>Tools</strong>: Frontend: React-Redux, customized CKEditor<br>Backend: Node, Express, PostgreSQL, Sequelize ORM; integration with Aspose API, Mailgun</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*As4-Fki-rgQ8F1D18etLYA.png" /></figure><h3>Service for locating C-level managers and improving board diversity and inclusion in the tech industry</h3><p><strong>Client</strong>: Technology executive and entrepreneur Sukhinder Singh Cassidy founded <a href="https://en.wikipedia.org/wiki/TheBoardlist">The Boardlist</a> to connect tech companies with qualified C-suite candidates who are women.</p><p><strong>Challenge: </strong>The client wanted us to change the service architecture, improve the DevOps infrastructure, migrate the service to a new stack and add search options and code coverage.</p><p><strong>Results</strong>: QuantumSoft revised the service, migrated more than 100,000 user accounts and led the project to production as a multiservice structure on AWS EC.</p><p><strong>Tools</strong>: TypeScript, React Redux, Nest.js, PostgreSQL, Type ORM, AWS ECS, Cypress, Mailchimp, Elasticsearch.</p><blockquote><strong>References</strong>:<br><a href="https://www.fastcompany.com/3058458/how-the-boardlist-plans-to-get-more-women-onto-startup-boards">How The Boardlist Plans To Get More Women Onto Startup Boards</a> — FastCompany</blockquote><blockquote><a href="https://en.wikipedia.org/wiki/TheBoardlist">https://en.wikipedia.org/wiki/TheBoardlist</a><br>The project story on Wikipedia</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=599da35c3c8d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building an app wired with ECG simulator]]></title>
            <link>https://quantumsoft.medium.com/building-an-app-wired-with-ecg-simulator-539c75ec957d?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/539c75ec957d</guid>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[xamarin-forms]]></category>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Mon, 13 Dec 2021 10:28:41 GMT</pubDate>
            <atom:updated>2021-12-13T10:28:41.997Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9p1J_Qjsm-qttl-mGfq1Q.jpeg" /><figcaption>Learning ECG techniques might not be easy</figcaption></figure><h3>Story</h3><p>Imagine you’re a nursing student with 12 electrodes in your hands and an ECG patient in front of you. What do you do?</p><p>Our colleagues at <a href="https://www.realityworks.com/">Realityworks</a> know that ECG tests require both skill and practice, so they built a simulator to teach the process more easily. Each electrode has a specific position on the body, although the number needed can vary from 3 to 12. Also, the specialist must recognize heart rhythms from the image patterns.</p><p>RealityWorks asked <a href="https://www.quantumsoft.pro/">QuantumSoft</a> engineers to build a <a href="https://www.realityworks.com/product/ecg-simulator/">mobile app</a> and asynchronous data exchange USB protocol to interact with a human-body simulator. But when we asked to see the mannequin prototype, we found out they didn’t have one yet!</p><p>They had just begun, so all we had was a tablet, circuit board, and a bunch of wires. Time to use our creativity! Together with our RealityWorks colleagues, we imagined how the simulator would work and look so we could design the interface of the app that would control the device.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Lpkeczf8MCT4lJqm" /><figcaption>QuantumSoft and Realityworks teams worked closely together</figcaption></figure><p>The app’s interface and functionality changed multiple times during the project, making our Agile skills critical to success. Some sprints ended with us needing to reverse our tasks to start the next sprint! However, we stuck to the plan — to release the first version as soon as possible.</p><blockquote><em>”Wait, the concept changed again? We just finished the new functionality!” — a common refrain during the project.</em></blockquote><p>Although we began at the idea level, it only took 6 months to reach our goal, from the first line of code to the ready-to-use version. The teams worked closely the whole time, with weekly meetings and daily contributions to the code base. We always provided the freshest versions to the hardware engineers so that they could immediately use it in their build.</p><p>Our team dug into the work and had a great time with their RealityWorks colleagues. We used a time tracker and a detailed plan to keep work steady but left room for creativity. We gave them as many opportunities as possible to put their hearts into designing the visual and engineering parts of the app.</p><p>On the RealityWorks side, they appreciated the results so much that they asked us to rework part of the app code so they could use it in other projects. And in March 2020, this ECG simulator won an <a href="https://www.realityworks.com/blog/realityworks-ecg-simulator-wins-2020-edison-award/">Edison Award</a>! It’s always gratifying to help clients, but it’s also nice to have external parties see the value of our work too!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Izga6tHkN4O4VX-ASbrrkA.jpeg" /><figcaption>Mastering ECG made easier</figcaption></figure><h3>Solution</h3><p>Our team started this project by building UX prototypes of the app interface. The requirements changed multiple times, so with every new sprint, the interface changed dramatically.</p><p>We chose Xamarin Forms as our main tool because it let us quickly create a cross-platform app on C#. The team developed several custom UI elements to enrich the interface and keep it uniform. To control the simulator, QuantumSoft engineers built an asynchronous data exchange protocol via USB for the device’s hardware.</p><p>The app has two modes, learning and exam. In learning mode, it checks the electrode placement on the mannequin and displays mistakes interactively. Learning mode can use 3 to 12 leads and can display the rhythms of a healthy heart versus a heart affected by certain conditions. In exam mode, the app shows images of heart rhythm patterns that the student must identify.</p><p>Available in English and Spanish, the app also has an administrator function for setup and selection of exam materials.</p><p>The project generated its first stable version in 6 months, with one to three engineers at different stages using Agile methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=539c75ec957d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Securing an Embedded System by Catching the Oversights]]></title>
            <link>https://quantumsoft.medium.com/securing-an-embedded-system-by-catching-the-oversights-35709fbefed6?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/35709fbefed6</guid>
            <category><![CDATA[embedded]]></category>
            <category><![CDATA[security-awareness]]></category>
            <category><![CDATA[security-checklist]]></category>
            <category><![CDATA[embedded-systems]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Fri, 19 Nov 2021 14:12:12 GMT</pubDate>
            <atom:updated>2021-11-19T14:14:02.420Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Before we dive in, I would like to thank </em><a href="https://www.linkedin.com/in/yankovitchgil/"><em>Gili Yankovitch</em></a><em> who was kind enough to spend his time discussing some items and reviewing the text.</em></p><p><em>Gili, that’s only the first one!</em></p><p>The ever-growing number of IoT, industrial, imaging, and other embedded devices flooding the markets is both exciting and scary. It’s no joke: millions of devices control and affect our lives in different ways. If a major, repetitive problem occurs in just a tiny fraction of the “fleet,” many systems could suffer.</p><p>This situation is scary because of robust security — namely, the lack of it. Devices are not well-protected, and the number of risks and remediation options is overwhelming.</p><h3>Importance of Security</h3><p>Creating a comprehensive security suite for a device is an art: too heavy and it stumbles over its own complexity, but too light makes for a brittle system. The art is in creating strong security without impeding the device’s functionality.</p><p>Many articles bring up the topic of security issues in embedded systems. While most are solid and truthful, they are scattered across the internet and sometimes give too-broad answers, like implementing secure FW upgrade or using Secure Boot mechanics.</p><p>Instead of adding yet another to the stack, I’ll touch on things that are either rarely discussed or everyone is silent about. Here are some unusual gaps and obstacles that you might have to deal with.</p><h3>Process Failures</h3><h3>No Threat Model</h3><p>The most obvious and equally common missing point is the absence of a <strong>threat model</strong>, “<em>a structured representation of all the information that affects the security of an application”</em> (definition courtesy of <a href="https://owasp.org/www-community/Threat_Modeling">OWASP author Victoria Drake</a>) and <strong>patterns/templates</strong> that clarify how to deal with unknowns.</p><p>Different teams advocate different approaches or techniques, such as Agile or Waterfall or whatever mix suits the situation. Regardless of the domain, security design should be considered before the development process even begins.</p><p>Having a threat model early in the product lifecycle won’t provide 100% security coverage, but it will eliminate excuses — any change should be reflected in it.</p><h3>No Decision-Made Records</h3><p>Experts agree that <strong>Architecture Decision Records</strong> (ADRs) or <strong>Architecturally-Significant Requirements</strong> (ASRs) define the best way to document solutions.</p><p><a href="https://github.com/joelparkerhenderson/architecture-decision-record">Github</a> offers examples of this flexible format. It would help to learn more about them and use them, in addition to maintaining threat model representations.</p><p>Document every decision made and log all action items and points provided. Ideally, each decision should link to the mitigation measures described in the first document.</p><h3>No CVE Tracking</h3><p>One important thing engineers rarely think of is maintaining a <strong>database of all</strong> <strong>the critical CVEs</strong> related to major hardware components (MPUs, MCUs, memory, etc.) in the hardware BOM.</p><p>To build said database:</p><ol><li>Download all current revisions of application notes (AN) and data sheets (DS) for each component and view the ChangeLog section.</li><li>Find vendor community forums and look for entries that mention a specific part number.</li><li>Contact the vendor and ask about problems that have yet to be disclosed. Helpful advice:</li></ol><ul><li>Use a company email address and word the request politely — be nice</li><li>Write on behalf of the company rather as an individual</li><li>Get a contact point or ask for a dedicated service engineer</li></ul><h3>Choice of Components</h3><h3>Limited selection of components</h3><p>Not all products suitable for the project are available within the project’s timeframe; they may be announced but only in development or unavailable for another reason.</p><p>Sometimes a business or startup doesn’t fit the expectations or requirements of a chosen vendor:</p><ul><li>low estimated volume</li><li>geopolitical circumstances (take into consideration political situation)</li><li>possibility of dual-use</li></ul><p>These criteria, coupled with the pandemic-generated chip shortage, make ordering parts difficult for many companies.</p><p>With security MCUs, even for simple documentation, a purchaser must prove to a vendor the firm intention to use the solution in the future. And that future must be bright and beneficial for the vendor.</p><h3>Suboptimal hardware choices</h3><p>Limited selection of components and poor hardware choices result in less-than-ideal decisions:</p><ul><li>Not being able to get an EVK in time to test all the features prevents reasonable choices. Full access to documentation is not enough to make the best judgment.</li><li>Time constraints or deadlines contribute to confusion and missteps</li><li>Reconsidering decisions also means updating the threat model, weighing the pros and cons of the new hardware, talking with vendors and finding alternatives.</li></ul><h3>Lack of hardware support for latest crypto algorithms</h3><p>Advances in software come faster than in hardware. Why? because it’s not an easy task to update existing hardware blocks with new and fancy algorithms. The situation gets complicated when we talk about new algorithms in cryptography (hashing or a new type of signature).</p><p>Advances and new things in the security field must undergo extensive analysis and continuous testing to ensure adequate security level before everyone believes they work (be time-tested).</p><p>Do not forget about certification that is usually time-consuming and costly, such as <a href="https://csrc.nist.gov/publications/detail/fips/140/2/final">FIPS 140</a> process and steps required to pass the validation.</p><p>For example, I needed a secure MCU that inherently supported ECC curves other than the default (e.g. Montgomery). I spent a lot of time pushing emails and checking part numbers before finding an appropriate solution (NXP, Infineon). Then I had to wait until things started rolling up.</p><p>Often, you must compromise: either sacrifice product security with a simpler solution or wait for new hardware and pray that the MVP can make its delivery deadline.</p><h3>Security Audit</h3><p>ideally, every security solution, and every firmware design as a whole, should be created by dedicated experts with solid knowledge in that particular area. Unfortunately, that is not always the case, as often all pieces are designed and implemented by Jack of all trades.</p><p>The good thing is that thinking about the need for security architecture is becoming prevalent these days. But how far does that thinking go?</p><h3>Lack of security review</h3><p>It’s OK for the security architecture to be designed and implemented by project engineers without security experts. A senior architecture engineer should be able to do that kind of job.</p><p>But arranging a review with a security expert is a must. All decisions and reasons for them should be documented (see first section) for reference.</p><h3>Expert knowledge shades affordable tradeoffs</h3><p>Although third-party experts are good for reviewing designs, they are not necessarily best at creating them. They may also cast shade on certain options to highlight preferred choices. Having engineers who oppose an expert’s opinion makes it easier to analyze potential tradeoffs.</p><h3>Absence of the security audit as a service</h3><ul><li><strong>D grade:</strong> discussing security architecture</li><li><strong>C</strong> <strong>grade:</strong> creating threat model and appropriate documentation</li><li><strong>B</strong> <strong>grade:</strong> mandating security audit</li><li><strong>A+</strong> <strong>grade:</strong> rolling out a CI/CD pipeline specifically for security</li></ul><h3>Discrepancies in expert opinions regarding foundational mathematics</h3><p>Security deals with cryptography and the latter is all about mathematics. Knowing the subject is a must, but practical experience is also very important. Experts will have varying depths of knowledge and experience, creating different views on the same problem that may confuse engineers.</p><p>Topics in cryptography may involve complex math concepts with few practical experiments and tests, or risks mitigation measures with unclear or unproven results.</p><h3>Over-designing</h3><h3>Excess enciphering</h3><p>Being paranoid is a must for a security expert. Indulging in the urge to scatter crypto primitives here and there (encrypting each piece of data stored on MCUs or protocols used to talk with peripherals) may introduce new bugs and errors because of the increased codebase.</p><p>Try to design simple things, as they are easy to review, discuss and scale.</p><h3>Too complex functionality breaks simplicity</h3><p>Sometimes hardware lacks the required capabilities and this issue only comes to light after the BOM list is approved, schematics are designed and development is in progress, so no hardware changes are allowed.</p><p>What happens next? Firmware accepts the challenge by implementing the missing parts! As a result the risk of introducing new vulnerabilities and errors increases.</p><p>Complex requirements cause complex, error-prone solutions.</p><h3>Conclusion</h3><p>I started thinking about the key ideas of this article before I began writing it. I didn’t want to elaborate on yet another bullet list of security-related items, even though they seem practical. Instead, I wanted to delineate what would be the focal point of the article:</p><p><strong><em>Security gaps are unpleasant things, but it’s OK. We all make mistakes and we learn from them. And the more we know, the more chill we can be when a crisis strikes.</em></strong></p><p><em>By </em><a href="http://www.linkedin.com/in/sergeidanielian"><em>Sergey Danielian</em></a><em>, Head of Embedded Systems, QuantumSoft</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35709fbefed6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Skyscrapers in IT]]></title>
            <link>https://quantumsoft.medium.com/skyscrapers-in-it-26f4590efb65?source=rss-e0cd69e80f0c------2</link>
            <guid isPermaLink="false">https://medium.com/p/26f4590efb65</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[systems-thinking]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-process]]></category>
            <dc:creator><![CDATA[QuantumSoft]]></dc:creator>
            <pubDate>Fri, 10 Sep 2021 13:22:05 GMT</pubDate>
            <atom:updated>2021-09-10T13:22:05.831Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*IuyN2E3uawVsx00_QsMFag@2x.jpeg" /></figure><p><em>“A designer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away”</em></p><p><em>Antoine de Saint-Exupéry</em></p><p>Software development is a complex, challenging process. A developer’s main problem may be the complexity of their domain and it can lead to an increase in support costs and loss of understanding how the system works as a whole. Rules and procedures are necessary for dealing with this problematic issue which leads developers towards the belief that software engineers should always start by simplifying things before scaling them into something more complicated or difficult to understand.</p><p>Many books on writing clean code, applying Object-Oriented Programming (OOP), design patterns, and SOLID principles focus solely on the level of creating a class or module. These regulations, however, do not provide enough guidance for complicated systems with numerous business logic needs that span across many subsystems.</p><p><em>Domain-Driven Design</em> (DDD) provides methods to decompose complex system structures into smaller chunks, while structuring subsystem components separately from each other in order to maintain focus within individual domain models.</p><p>The purpose of this article is to popularize DDD and focus on strategic concepts, which is often given the least attention when applying this approach.</p><h3>A Golden Hammer For Golden Nails</h3><p>Before we dive into the details of domain-driven design, we first need to ask whether we are using a “golden hammer” and then we should try to understand which tool is best for our purposes. When choosing a system implementation method, the key factor is to reduce the complexity and cost of development. According to Martin Fowler’s classification, there are two ways to structure your business layer:</p><ol><li>Transaction scripts</li><li>Domain models</li></ol><p>To help you keep track of the procedures in your code, a transaction script may be beneficial. In most situations, it will adequately suffice for application development. The following steps might be included in a separate script: validating input data, verifying authorization, checking business rules, and updating the model’s state into a database. The service layer is identical to the database transaction boundary. Sometimes the service layer is extracted as it allows for code sharing across scenarios.</p><p>This approach has its advantages: simplicity and speed of implementation. Disadvantages can appear as the system grows. Signs of problems can manifest as the following:</p><ul><li>Entities do not control the correctness of changing their state;</li><li>An increase side effects in a business scenario that cannot be completed in a reasonable amount of time within a single transaction;</li><li>Anemic models, when most of the logic is scattered across service classes and model classes are left without behavior, which leads to the developers losing sight of the overall picture and communication with the subject area.</li></ul><p>It is feasible to convert a transaction scenario into domain modeling, but it is time-consuming and may necessitate significant refactoring and communication. To make the best choice, we’ll need to assess the requirements for the future system as well as anticipate how long it will take to build it, the number of use cases involved, the number of roles that will be needed in business processes, and external system integration.</p><p>Based on personal experience, I can say that one of the simplest and most indicative signs of complexity is the estimated time period for development. If the preliminary assessment for the project is within one or two years and that is when the active development of the system ends and it goes into support mode, it is likely that the cost of finding an exact domain model will not pay off.</p><p>If the time period implies active development for three years or more, you should pay attention to the other requirements, while also taking into account the amount of human resources needed to complete the project. The most detailed information about the complexity inherent in software systems is described in Grady Booch’s book [4] in the “Complexity” chapter.</p><h3>Practical design</h3><p>The story of the Tower of Babel indicates that one of the most essential ingredients for success is a firm grasp on <strong><em>objectives and effective communication</em></strong>. Immersion in the domain is an important aspect of software development.</p><p>Throughout this time, the developer is exposed to a wide range of new words and techniques. DDD makes it simple to learn about the domain. The developers should interact with domain experts during system design by asking questions and ensuring that both the developer and the expert are on the same page in terms related to those words.</p><p>As a result of the natural process of communication, a single glossary should be established. In this instance, the single glossary is not a list of specialist words from the domain; instead, it incorporates important terms from both domains.</p><p>In DDD, this concept is called a <em>ubiquitous language</em>. It is worth noting that this is very similar to the principles that underlie OOP for designing classes and their interfaces. DDD tries to elevate this idea to an absolute so that even an expert looking at the code can understand and ensure that the program is correct. Therefore, it is imperative that all the terms are clear and consistent. In the process of developing a ubiquitous language, it is also worth paying attention to how consistent the terms are with each other.</p><p>Software systems are built to solve business problems. The field in which your business operates is your <em>domain</em>. In any business, there are both general aspects that are common for any field, and <em>specialized</em> ones which are unique to that domain. This is also true for information systems, which also have <em>generic</em> <em>subdomains</em>, such as user identification, notification sending, and payments.</p><p>It should be emphasized that in any system there is always a part that is key to the business. This subdomain is the <em>core</em> of the domain. The main efforts should be concentrated on building a quality system core. Defining the subdomains allows you to split up the domain logically based on business processes. This makes it easy to build a <em>context map</em> that defines the boundaries of the physical partition at the code level and describes the types of interaction between the contexts.</p><p>The part of the system that encapsulates the business processes from one or more subdomains but does not violate the integrity of the ubiquitous language is called the <em>bounded context</em>. With a properly decomposed system, it is not necessary at all to implement all parts of the system using the DDD approach. For individual parts, a simpler option with a transaction script can be used. Another advantage of this decomposition is the possibility to use ready-made solutions for generic subdomains.</p><p>After identifying the most important bounded context, it is necessary to delve into the features to study the model. Model design is the process of displaying the business processes and terms of a bounded context in the form of a set of classes and methods that allow you to effectively resolve business problems. For this purpose, DDD offers a number of tactical patterns that help in building a domain model: aggregate, entity, value object, domain events, and others.</p><p>The process of cognition is iterative since it is impossible to immediately cover everything. In the first iteration, the data model is just a starting point, after which a long process of knowledge processing and displaying it on a new model is required. Eric Evans, the author of the DDD concept, introduced the concept of “distillation” to describe the process of improving the model.</p><p>The merging of words with the same name but different meanings from various constrained contexts is one of the most typical instances of a lack of communication between experts and coders. This creates a class with low cohesion since some methods and fields are used in some user scenarios without dependence on the others, resulting in excessive coupling between bounded contexts. It also lowers the likelihood that they might develop independently.</p><p>Let’s apply the aforementioned ideas to an example from the field of software development services. The examples were created to illustrate the concepts in action. This would take a long time in practice for the domain model to form in a real system, and that is reasonable.</p><p>A website must be designed that enables potential customers to submit requests for the deployment of software solutions, after which allows them to join up. The system should automatically assign a manager to each request as soon as it is submitted. Requests can either be accepted or rejected. A cover letter should be sent if a request is denied.</p><p>If a proposal is accepted, the client will receive an offer letter. The client will have access to their own account after the contract has ended, allowing them to establish and manage their team. They should also be able to create projects, add activities, and assign team members to projects.</p><p>After analyzing the domain, the following contexts have been distinguished:</p><ul><li>onboarding</li><li>collaboration</li><li>development management</li><li>notifications</li><li>user identification</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*tjbMMIxt_NyDHlDRAmofQA@2x.jpeg" /><figcaption>Bounded context map</figcaption></figure><p>In the contexts of onboarding and notifications, there is an Event entity for both that has the same name but completely different semantics. In the first case, it is a planned meeting of a representative and a potential client, but in the second, this entity describes business events in the system that the user has the opportunity to subscribe to. In contrast to the previous example, sometimes the same physical object in the real world can be described in different terms in different contexts.</p><p>It is easy to see in the example of the person submitting a request on the site. In the context of onboarding, they play the role of a potential client, but after signing up on the platform, they have different responsibilities depending on the context in which they are interacting with the system.</p><p>In the context of collaboration, they will be responsible for the organization and they will be able to create teams and add participants and determine their roles, but in the context of notifications, they are a subscriber and should be able to manage their subscriptions, but they can also be assigned to tasks in the context of development management. If we insisted on merging these terms into a single User entity, it would be harder to understand and develop the system, as well as blur the boundaries of class responsibility in various contexts.</p><p>This is a very common occurrence in large systems. There are typically one or two “god objects” which accumulate a huge amount of functionality which should fit in various different contexts, but it’s always easier to just add one more method or one more database column. When analyzing requirements and defining contexts, you should be guided by the roles and responsibilities that are assigned to the entity. This will help you avoid a <em>big ball of mud</em> architecture.</p><h3>Off by a meter, can we just move it?</h3><p>The Leaning Tower of Pisa is a beautiful and iconic landmark that attracts millions of tourists each year. But, the constant repairs it needs are very costly for Italy’s government. The tower was designed to lean because there were not enough people on site when construction began in 1173 who had any architectural experience or knowledge — so they just built what looked good at the time without making sure things would work with gravity. It took almost 100 years before anyone realized a mistake had been made; but instead of fixing it right away, we let them continue building other buildings around this new design flaw as well which lead to all sorts more problems over time including cracks from earthquake damage and sinking foundations due to heavier construction materials now being used than back then.</p><p>And this is the very example that we encounter every time in practice when developing software systems, when requirements change over time and with the growth of the system and it becomes necessary to add new functionality. Often when developing complex software systems or startups, there are no exact deadlines, and not all of the requirements are known in advance, so when taking that into account, we need an approach that will reduce the risks of choosing a particular technology or framework.</p><p>DDD is not linked to any technology, language, or paradigm. It can be used equally well for both object-oriented and functional languages​. There are many different architectural styles for implementing applications. One of the key benefits of DDD is that this approach focuses on building the business core. This allows you to postpone or revise some technical solutions based on new factors, without significantly increasing the cost of changes, which provides the best conditions for the system to develop naturally.</p><p>Traditionally, most programs start being developed as monolithic applications. This is the right path at the initial stage when there is not enough knowledge of the domain to clearly define bounded context boundaries. Over time, the systems grow to enormous sizes, and then the development of monolithic systems becomes difficult. A recently popular way to further develop systems is microservice architecture. If you need to move from a monolith to a microservice architecture, the decomposition of monolithic systems that are built taking into account DDD principles will naturally occur along context boundaries.</p><h3>Populating</h3><p>I find that the Colosseum is a wonderful example of architecture as it doesn’t require complex explanations to be understood. The simplicity and conciseness also show in modern-day systems such as those created by developers, which aim at building structures you can admire for their beauty without having extensive knowledge about them.</p><p>The design of this system is a sophisticated process that relies on intention, communication, and thoughtful consideration. When looking for the best architecture it’s important to look at the systems from different angles in order to gauge what patterns exist across all levels. Developers who are guided by these rules will not lose sight of an overall picture while improving single parts within their model.</p><p>The main factors contributing to this are decomposition of the system into bounded contexts, maintaining a ubiquitous language for every team member involved in development — ensuring that everyone is on the same page and all knowledge can be disseminated quickly without confusion as well as continuous refactoring based on new knowledge about the domain. This approach to system decomposition also makes it possible to effectively organize development teams with distinct responsibilities per project (i.e., design-development pairs) along with being able to scale individual parts of them when needed or desired from one production environment at any point in time.</p><p><em>By Michael Lazko, Senior Backend Developer at QuantumSoft</em></p><h3>Glossary</h3><p><em>Ubiquitous language </em>is the language structured around the domain model and used by all the team members to describe the business processes and rules in the software development process.</p><p><em>Domain </em>is the field of knowledge, influence, or activity.</p><p><em>Core of the domain </em>is the most important part of the domain model, central to the user’s goals and what makes it valuable to the business.</p><p><em>Bounded context</em> is the context in which the single language and corresponding model are valid. We can include one or more subdomains.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=26f4590efb65" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>