<?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 Gene Kuo on Medium]]></title>
        <description><![CDATA[Stories by Gene Kuo on Medium]]></description>
        <link>https://medium.com/@genekuo?source=rss-9e756a6b0e7d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*FbZUWij_VsM9rNnjmYP8mw.jpeg</url>
            <title>Stories by Gene Kuo on Medium</title>
            <link>https://medium.com/@genekuo?source=rss-9e756a6b0e7d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 08:01:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@genekuo/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[Using HashiCorp Vault as Certificate Issuer on a Kubernetes Cluster]]></title>
            <link>https://genekuo.medium.com/using-hashicorp-vault-as-certificate-manager-on-a-kubernetes-cluster-155604d39a60?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/155604d39a60</guid>
            <category><![CDATA[vault]]></category>
            <category><![CDATA[tls]]></category>
            <category><![CDATA[secrets]]></category>
            <category><![CDATA[certificate]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Mon, 13 Mar 2023 13:02:53 GMT</pubDate>
            <atom:updated>2023-03-13T13:05:20.097Z</atom:updated>
            <content:encoded><![CDATA[<h4>In this article, we will set up HashiCorp vault as a certificate issuer using the HashiCorp Vault PKI engine and cert-manager as the management of certificates. We will demonstrate how the certificate issuing and automatic renewal works when we deploy an example web application with ingress resources and TLS enabled. This can simplify the usual manual process of certificate requesting, signing, and renewal. The following figure is the high-level view of the implementation.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*sVI78ewNgqE8a7L6LuIhJQ.png" /></figure><h4><em>Installing HashiCorp Vault</em></h4><p>To install HashiCorp Vault on a Kubernetes cluster, we will add the Vault chart to our Helm repository and retrieve the update from the remote repository. We then deploy Vault using Helm with the injector disabled.</p><pre>helm repo add hashicorp https://helm.releases.hashicorp.com<br><br>helm repo update<br><br>helm install vault hashicorp/vault --set &quot;injector.enabled=false&quot;</pre><p>After installation, the vault pod created will not be ready since the vault is not initialized and unsealed yet. We will have to initialize and unseal the vault to get the master key which gives access to the data stored in the vault by encryption/decryption.</p><pre>kubectl get po</pre><h4><em>Initializing and unsealing the vault</em></h4><p>When the vault is initiated, it will be in sealed mode, meaning it can access the storage layer but cannot decrypt the content. So, we will initialize the vault and distribute the unseal key using Shamir’s Secret algorithm with one key share and one key threshold. The resulting unseal key and initial root token is written to init-keys.json.</p><pre>kubectl exec vault-0 -- vault operator init -key-shares=1 -key-threshold=1 -format=json &gt; init-keys.json</pre><p>We can view the unseal key in init-keys.json using the following commands and save it in an environment variable. We then exec into vault-0 to unseal the vault running on it with VAULT_UNSEAL_KEY.</p><pre>cat init-keys.json | jq -r &quot;.unseal_keys_b64[]&quot;<br><br>VAULT_UNSEAL_KEY=$(cat init-keys.json | jq -r &quot;.unseal_keys_b64[]&quot;<br><br>kubectl exec vault-0 -- vault operator unseal $VAULT_UNSEAL_KEY</pre><p>After the unsealing process is complete, we can check that the vault-0 pod appears in a ready state.</p><pre>kubectl get po</pre><h4><em>Configuring the Vault PKI engine as a Certificate Authority</em></h4><p>The init-keys.json also contains the initial root token we can use to log in to configure the vault. We will retrieve it and set it in an environment variable called VAULT_ROOT_TOKEN to log in to the vault and configure the PKI engine as a certificate authority.</p><pre>cat init-keys.json | jq -r &quot;.root_token&quot;<br>VAULT_ROOT_TOKEN=$(cat init-keys.json | jq -r &quot;.root_token&quot;)</pre><p>After logging into the vault with the root token, we can enable the PKI engine, and configure ttl of the PKI engine to 8760 hours.</p><pre>kubectl exec vault-0 -- vault login $VAULT_ROOT_TOKEN<br>kubectl exec --stdin=true --tty=true vault-0 -- /bin/sh<br>vault secrets enable pki<br>vault secrets tune -max-lease-ttl=8760h pki</pre><p>To configure the PKI engine as CA, we will generate a self-signed root certificate for signing certificates and set its ttl to 8760 hours, and write to a file called demo-root-ca.json.</p><pre>vault write -format=json pki/root/generate/internal \<br>    common_name=&quot;Demo Root Certificate Authority&quot; &gt; /tmp/demo-root-ca.json<br>cat /tmp/demo-root-ca.json<br><br>vault write pki/root/generate/internal \<br>    common_name=example.com ttl=8760h</pre><p>We will then configure the PKI engine certificate issuing and certificate revocation list (CRL) endpoints of the vault services in the default namespace.</p><pre>vault write pki/config/urls \<br>    issuing_certificates=&quot;http://vault.default:8200/v1/pki/ca&quot; \<br>    crl_distribution_points=&quot;http://vault.default:8200/v1/pki/crl&quot;</pre><p>According to the architecture shown at the beginning of the article, we need to create a role that enables the creation of the certificates under the condition for <em>example.com</em> domain with any subdomains, and a policy that defines finer-grained permissions.</p><pre>vault write pki/roles/example-dot-com \<br>    key_type=any \<br>    allowed_domains=example.com \<br>    allow_subdomains=true \<br>    max_ttl=5m</pre><p>Once we have the role created, we can proceed to make a policy named pki for the corresponding vault PKI role.</p><pre>vault policy write pki - &lt;&lt;EOF<br>path &quot;pki*&quot; { capabilities = [&quot;read&quot;, &quot;list&quot;] }<br>path &quot;pki/roles/example-dot-com&quot;   { capabilities = [&quot;create&quot;, &quot;update&quot;] }<br>path &quot;pki/sign/example-dot-com&quot;    { capabilities = [&quot;create&quot;, &quot;update&quot;] }<br>path &quot;pki/issue/example-dot-com&quot;   { capabilities = [&quot;create&quot;] }<br>EOF</pre><h4><em>Enable the Kubernetes authentication method</em></h4><p>To simplify how applications interact with Vault, we will use Kubernetes auth method. Kubernetes auth method makes use of JWT associated with Kubernetes Service Account.</p><p>To configure the auth method, we will use the local token and CA certificate created when the vault pod is started, which is located on the default mount folder /var/run/secrets/kubernetes.io/serviceaccount/ . Vault will periodically re-read the files in this folder to support short-lived tokens.</p><p>When an application tries to interact with Vault, Vault uses this configuration to verify and retrieve the application’s identity with the Kubernetes API server and its TokenReview API.</p><pre>vault auth enable kubernetes<br><br>vault write auth/kubernetes/config \<br>    token_reviewer_jwt=&quot;$(cat /var/run/secrets/kubernetes.io/serviceaccount/token)&quot; \<br>    kubernetes_host=&quot;https://$KUBERNETES_PORT_443_TCP_ADDR:443&quot; \<br>    kubernetes_ca_cert=@/var/run/secrets/kubernetes.io/serviceaccount/ca.crt</pre><p>We will then create a Kubernetes authentication role named issuer that binds the pki the policy defined earlier with a Kubernetes service account name and namespaces.</p><pre>vault write auth/kubernetes/role/issuer \<br>    bound_service_account_names=issuer \<br>    bound_service_account_namespaces=cert-manager,default \<br>    policies=pki \<br>    ttl=20m<br><br>exit</pre><p>After the above configuration, the Vault with the PKI engine can act as CA and for the application (cert-manager) to interact with Vault and authenticate through Kubernetes auth method (TokenReviewer API).</p><p>Upon authentication, Vault will retrieve the policy defined for the role of the service account issuer. Vault can then issue certificates according to the permissions in the policy.</p><h4><em>Installing cert-manager, configuring issuer, and creating a certificate</em></h4><p>We will install Cert-Manager to interact with the vault PKI to issue certificates. After installation, we can check the custom resource definitions and pod created.</p><pre>helm repo add jetstack https://charts.jetstack.io<br>helm repo update<br>helm install \<br>    cert-manager jetstack/cert-manager \<br>    --namespace cert-manager --create-namespace \<br>    --version v1.11.0 --set installCRDs=true<br>kubectl get crds<br>kubectl get po -n cert-manager</pre><p>We will then create a service account called issuer and service account token as a Secret resource. This secret will be referenced in the cert-manager Issuer resource to authenticate with Vault via Kubernetes auth method when generating and issuing certificates.</p><pre>kubectl create serviceaccount issuer<br>kubectl get sa<br>kubectl apply -f secret.yaml<br>kubectl get secrets<br>kubectl describe secret issuer-token<br>kubectl get secret issuer-token -o jsonpath={.data.token} | base64 -d</pre><pre>apiVersion: v1<br>kind: Secret<br>metadata:<br>  name: issuer-token<br>  annotations:<br>    kubernetes.io/service-account.name: issuer<br>type: kubernetes.io/service-account-token</pre><p>We can now create a cert-manager Issuer resource that references the issuer token and role for authentication against Vault, Vault PKI certificate issuing endpoint, and Vault server URL, as in the following.</p><pre>apiVersion: cert-manager.io/v1<br>kind: Issuer<br>metadata:<br>  name: vault-issuer<br>  namespace: default<br>spec:<br>  vault:<br>    server: http://vault.default:8200<br>    path: pki/sign/example-dot-com<br>    auth:<br>      kubernetes:<br>        mountPath: /v1/auth/kubernetes<br>        role: issuer<br>        secretRef:<br>          name: issuer-token<br>          key: token</pre><pre>kubectl apply -f issuer.yaml<br>kubectl get issuer<br>kubectl describe issuer vault-issuer</pre><p>Finally, we can create a cert-manger Certificate resource with a created secret containing a certificate that is issued by Vault. The Certificate resource is managed by the cert-manager.</p><pre>apiVersion: cert-manager.io/v1<br>kind: Certificate<br>metadata:<br>  name: demo-example-com<br>  namespace: default<br>spec:<br>  secretName: example-com-tls<br>  issuerRef:<br>    name: vault-issuer<br>  commonName: demo.example.com<br>  dnsNames:<br>  - demo.example.com</pre><pre>kubectl apply -f certificate.yaml<br>kubectl get certificate<br>kubectl describe certificate demo-example-com<br><br>kubectl get secrets example-com-tls<br>kubectl describe secrets example-com-tls</pre><h4><em>Install ingress-nginx controller</em></h4><p>To demonstrate applications deployed on the Kubernetes cluster to make use of Vault and cert-manager to issue and manage certificates, we will deploy a demo web application and enable TLS through an ingress resource. First, we will deploy an ingress-nginx controller to the Kubernetes cluster using Helm.</p><pre>helm upgrade --install ingress-nginx ingress-nginx \<br>    --repo https://kubernetes.github.io/ingress-nginx \<br>    --namespace ingress-nginx --create-namespace</pre><p>We then create a deployment and a service for the web application.</p><pre>kubectl create deployment web --image=gcr.io/google-samples/hello-app:1.0<br>kubectl expose deployment web --port=8080<br>kubectl get svc web</pre><p>Within the ingress manifest, we enable TLS by including a tls section in the manifest file to reference the secret containing the certificate issued.</p><pre>apiVersion: networking.k8s.io/v1<br>kind: Ingress<br>metadata:<br>  name: example-ingress<br>  annotations:<br>    kubernetes.io/ingress.class: &quot;nginx&quot;<br>spec:<br>  tls:<br>  - hosts:<br>    - demo.example.com<br>    secretName: example-com-tls<br>  rules:<br>  - host: demo.example.com<br>    http:<br>      paths:<br>      - path: /<br>        pathType: Prefix<br>        backend:<br>          service:<br>            name: web<br>            port:<br>              number: 8080</pre><pre>kubectl apply -f ingress.yaml<br>kubectl get ingress</pre><p>To simulate the domain name resolution on the local machine. We can edit the hosts file with sudo vi /etc/hosts .</p><pre>127.0.0.1 demo.example.com</pre><p>We can test the application by browsing <a href="https://demo.example.com/">https://demo.example.com</a> and verifying the certificate according to your browser.</p><p>We can also verify and show TLS handshake details by running the following command. From the output of this command, we can see the start date, expire date, and issuer info of the issued certificate is correct based on our configuration (valid for 5 minutes).</p><pre>curl -kivL https://demo.example.com</pre><p>Either from the browser window or curl command, we can also demonstrate the automatic certificate renewal by refreshing the browser or rerunning the curl command after 5 minutes according to our setup. We can see that it has automatically renewed values for start date and expire date.</p><h4>Conclusion</h4><p>The Kubernetes auth method simplifies how an application (cert-manager) uses Kubernetes Service Account to authenticate and interact with HashiCorp Vault. HashiCorp Vault PKI engine act as a Certificate Authority to simplify the issuing process of certificates which can be managed by the cert-manager automatically and efficiently, such as certificate renewal.</p><p>The are many other use cases from HashiCorp Vault in cloud-native platforms or applications that we can apply, such as application secret injection and management.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=155604d39a60" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Configuring A Secured Primary Network Infrastructure on AWS]]></title>
            <link>https://genekuo.medium.com/configuring-a-secured-primary-network-infrastructure-on-aws-754c4c3fee2c?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/754c4c3fee2c</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[networking]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Thu, 21 Oct 2021 04:15:49 GMT</pubDate>
            <atom:updated>2021-10-21T04:15:49.887Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bVM95Lgyh30O1j5M" /><figcaption>Photo by <a href="https://unsplash.com/@bracht?utm_source=medium&amp;utm_medium=referral">Fabio Bracht</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>This article is a guideline for configuring a primary network infrastructure on AWS to securely control network access to networking resources in AWS. We will use several AWS networking services and provide Terraform resource blocks to help us understand how to set up a primary network infrastruture in an Infrastrucure as Code (IaC) way.</blockquote><h4>Primary Network Infrastructure</h4><p>The primary network infrastructure on AWS we are going to talk about is a common network configuration that can be set up to be extended further to add application-related infrastructure on top of it to fulfill specific application or system requirements. This infrastructure is shown as follows. We will talk about the guidelines of configuring its major components in the following sections.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*HitMIsLGlSlbkxTf5Rmntg.png" /></figure><h4>Virtual Private Cloud (VPC)</h4><p>A VPC is a logically isolated virtual network on AWS cloud where we can launch AWS resources there. A VPC resides within an AWS region.</p><p>We will need to specify a Classless Inter-Domain Routing (CIDR) block to create our VPC. This is the range of IP addresses that will be available for use in the network. In terms of IPv4 addresses, the CIDR block can be represented such as 10.0.0.0/24 which contains 256 addresses. Since AWS reserves 5 IP addresses within each subnet, there can be a maximum of 251 IP addresses available for use in a VPC with a single subnet.</p><p>We don’t use the default VPC created automatically by AWS. The default VPC includes public subnets and an internet gateway and will not be considered secure when we create AWS resources in it like EC2 instances.</p><pre>resource &quot;aws_vpc&quot; &quot;main&quot; {<br>  cidr_block           = var.cidr_block</pre><pre>  tags = {<br>    Name   = var.vpc_name<br>  }<br>}</pre><h4>Subnets</h4><p>Subnets contain the partial range of the IP addresses in the VPC. A subnet resides within a specific availability zone and belonged to a VPC. We can only launch EC2 instances in a subnet.</p><p>We will create two public subnets (var.public_subnets_count = 2)and two private subnets (var.private_subnets_count = 2) in different availability zones for high availability. Each subnet has its own CIDR block that is a subset of the VPC CIDR block.</p><pre>// 2 Public Subnets<br>resource &quot;aws_subnet&quot; &quot;public_subnets&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = &quot;10.0.${count.index * 2 + 1}.0/24&quot;<br>  availability_zone       = element(var.availability_zones, count.index)<br>  map_public_ip_on_launch = true</pre><pre>  count = var.public_subnets_count</pre><pre>  tags = {<br>    Name   = &quot;public_10.0.${count.index * 2 + 1}.0_${element(var.availability_zones, count.index)}&quot;<br>  }<br>}</pre><pre>// 2 Private Subnets<br>resource &quot;aws_subnet&quot; &quot;private_subnets&quot; {<br>  vpc_id                  = aws_vpc.main.id<br>  cidr_block              = &quot;10.0.${count.index * 2}.0/24&quot;<br>  availability_zone       = element(var.availability_zones, count.index)<br>  map_public_ip_on_launch = false</pre><pre>  count = var.private_subnets_count</pre><pre>  tags = {<br>    Name   = &quot;private_10.0.${count.index * 2}.0_${element(var.availability_zones, count.index)}&quot;<br>  }<br>}</pre><h4>Internet Gateway (IGW)</h4><p>The previous section for creating public and private subnets by default makes those subnets private that there is no connection between a subnet and the public internet. We will need to configure Internet Gateway and Route Tables to make subnets public.</p><p>Internet Gateway is associated with the VPC and is used to provide internet connectivity to EC2 instances within the public subnet. It maps an instance’s private IP address with an associated public or Elastic IP address and then routes traffic outside the subnet to the internet.</p><p>To connect an instance in our VPC to the public internet, we will need to specify how to route traffic to the public internet in a Route Table. We will later define a public route table with a specific route to route traffic from public subnets to the IGW.</p><pre>resource &quot;aws_internet_gateway&quot; &quot;igw&quot; {<br>  vpc_id = aws_vpc.main.id</pre><pre>tags = {<br>    Name   = &quot;igw_${var.vpc_name}&quot;<br>  }<br>}</pre><h4>Public Route Table</h4><p>Route Tables define a set of rules called routes about how traffic is routed throughout our VPC. Each route consists of a destination and a target. If traffic is being sent to an IP address within the destination CIDR block, then the traffic is directed to the route’s target.</p><p>When we create a VPC, a route table is automatically created and attached to the VPC. It is called the main route table with a single route that has the destination CIDR block as that of the VPC, and the target is local. This allows resources in the VPC to communicate with each other.</p><p>Instead of modifying the main route table, we will create a new route table with a destination of 0.0.0.0/0 and target internet gateway id, and associate it with our public subnets. When we create a new route table, the local route will automatically be created as well.</p><pre>resource &quot;aws_route_table&quot; &quot;public_rt&quot; {<br>  vpc_id = aws_vpc.main.id</pre><pre>  route {<br>    cidr_block = &quot;0.0.0.0/0&quot;<br>    gateway_id = aws_internet_gateway.igw.id<br>  }</pre><pre>  tags = {<br>    Name   = &quot;public_rt_${var.vpc_name}&quot;<br>  }<br>}</pre><pre>resource &quot;aws_route_table_association&quot; &quot;public&quot; {<br>  count          = var.public_subnets_count<br>  subnet_id      = element(aws_subnet.public_subnets.*.id, count.index)<br>  route_table_id = aws_route_table.public_rt.id<br>}</pre><h4>NAT Gateway</h4><p>A NAT Gateway allows our instances in private subnets to send traffic out of our VPC to the public internet, but not in the other direction.</p><p>The NAT Gateway will be created in a public subnet and will forward the outbound traffic to the VPC’s internet gateway and then out to the public internet, but not allow inbound traffic from the public internet to reach the private subnets. After the NAT gateway is configured, we will need to add a route to the private route table to point to the NAT Gateway.</p><pre>// Static IP for Nat Gateway<br>resource &quot;aws_eip&quot; &quot;nat&quot; {<br>  vpc = true</pre><pre>tags = {<br>    Name   = &quot;eip-nat_${var.vpc_name}&quot;<br>  }<br>}</pre><pre>// Nat Gateway<br>resource &quot;aws_nat_gateway&quot; &quot;nat&quot; {<br>  allocation_id = aws_eip.nat.id<br>  subnet_id     = element(aws_subnet.public_subnets.*.id, 0)</pre><pre>tags = {<br>    Name   = &quot;nat_${var.vpc_name}&quot;<br>  }<br>}</pre><h4>Private Route Table</h4><p>If traffic in private subnets is routed through the NAT gateway, it will not be publicly accessible, in contrast to the traffic in public subnets is routed to the internet gateway and is publicly accessible.</p><p>So we need to create another route table consisting of a route to connect our private subnets to the NAT gateway. The route in the route table has a destination of 0.0.0.0/0 and a target of our NAT Gateway and associated with our private subnets.</p><pre>// Private Route Table<br>resource &quot;aws_route_table&quot; &quot;private_rt&quot; {<br>  vpc_id = aws_vpc.main.id</pre><pre>  route {<br>    cidr_block     = &quot;0.0.0.0/0&quot;<br>    nat_gateway_id = aws_nat_gateway.nat.id<br>  }</pre><pre>  tags = {<br>    Name   = &quot;private_rt_${var.vpc_name}&quot;<br>  }<br>}</pre><pre>// Associate private subnets to private route table<br>resource &quot;aws_route_table_association&quot; &quot;private&quot; {<br>  count          = var.private_subnets_count<br>  subnet_id      = element(aws_subnet.private_subnets.*.id, count.index)<br>  route_table_id = aws_route_table.private_rt.id<br>}</pre><h4>Security Groups</h4><p>So far the instances in public subnets can be exposed to the internet through internet gateway, and the instances in private subnets can reach the internet but we cannot SSH into the instances in private subnets because of NAT gateway. We will need to create a bastion host instance in our public subnets that allow us to SSH into the instances in the private subnets from the bastion host. Before that, we will talk about security groups.</p><p>Security groups act as virtual firewalls for our EC2 instances, controlling both inbound and outbound traffic at the instance level. Each inbound rule consists of a source, protocol, and port range. Each outbound rule consists of destination, protocol, and port range. An example of an outbound rule might be destination: 0.0.0.0/0, protocol number: TCP(6), and port range: 443. This rule specifies that outbound traffic from the instance, destined for any IP address, using TCP protocol, on port 443 is allowed.</p><p>For the bastion host, we will create a security group with an inbound rule as follows to allow SSH access to the bastion host, associate this security group with the bastion host that will be created later. This inbound rule (ingress) will allow traffic on port 22 from anywhere. The CIDR blocks can also be limited to your own public IP address or network address to enhance security.</p><pre>resource &quot;aws_security_group&quot; &quot;bastion_host&quot; {<br>  name        = &quot;bastion_sg_${var.vpc_name}&quot;<br>  description = &quot;Allow SSH from anywhere&quot;<br>  vpc_id      = aws_vpc.main.id</pre><pre>egress {<br>    from_port   = 0<br>    to_port     = 0<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }</pre><pre>ingress {<br>    from_port       = 22<br>    to_port         = 22<br>    protocol        = &quot;tcp&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }</pre><pre>tags = {<br>    Name   = &quot;bastion_sg_${var.vpc_name}&quot;<br>  }<br>}</pre><h4>Bastion Host</h4><p>A bastion host instance will be created in our public subnet and will route SSH traffic from our local network over EC2 instances in our private subnets by setting up a secure SSH tunnel.</p><p>In addition to an Amazon 2 Linux machine image we choose for our bastion host, we need to attach an SSH key pair to be able to access SSH to the bastion host with the private key. The public key should be put in the file specified in file(var.public_key) from our variable file.</p><p>We then need to provide a layer of security for our instance by associating the bastion host with the security group created previously.</p><p>And the bastion host will be created within our public subnet.</p><pre>data &quot;aws_ami&quot; &quot;bastion&quot; {<br>  most_recent = true<br>  owners = [&quot;amazon&quot;]</pre><pre>  filter {<br>    name   = &quot;name&quot;<br>    values = [&quot;amzn2-ami-hvm-*-x86_64-ebs&quot;]<br>  }<br>}</pre><pre>// Key Pair<br>resource &quot;aws_key_pair&quot; &quot;main&quot; {<br>  key_name   = &quot;main&quot;<br>  public_key = file(var.public_key)<br>}</pre><pre>resource &quot;aws_instance&quot; &quot;bastion&quot; {<br>  ami           = data.aws_ami.bastion.id<br>  instance_type = var.bastion_instance_type<br>  key_name = aws_key_pair.main.id<br>  vpc_security_group_ids = [aws_security_group.bastion_host.id]<br>  subnet_id = element(aws_subnet.public_subnets, 0).id<br>  associate_public_ip_address = true</pre><pre>  tags = {<br>    Name = &quot;bastion&quot;<br>  }<br>}</pre><p>We can then use the Terraform outputs.tf to output the IP address of the bastion host in the terminal when we run terraform apply as follows.</p><pre>output &quot;bastion&quot; {<br>  value = aws_instance.bastion.public_ip<br>}</pre><p>After terraform apply completes, we can set up an SSH tunnel to access private instances from our local machines.</p><pre>ssh -L [LOCAL_IP:]LOCAL_PORT:DESTINATION_PRIVATE_IP:DESTINATION_PORT ec2-user@BASTION_IP</pre><p>In addition, when we create EC2 instances within the private subnets to be accessible from the bastion host in the public subnet, we will create a security group and associate it to these instances as follows.</p><pre>resource &quot;aws_security_group&quot; &quot;server_sg&quot; {<br>  name        = &quot;server_sg&quot;<br>  description = &quot;Allow traffic on port 8080 and enable SSH&quot;<br>  vpc_id      = aws_vpc.main.id</pre><pre>  ingress {<br>    from_port       = &quot;22&quot;<br>    to_port         = &quot;22&quot;<br>    protocol        = &quot;tcp&quot;<br>    security_groups = [aws_security_group.bastion_host.id]<br>  }</pre><pre>  ingress {<br>    from_port       = &quot;8080&quot;<br>    to_port         = &quot;8080&quot;<br>    protocol        = &quot;tcp&quot;<br>    cidr_blocks = [var.cidr_block]<br>  }</pre><pre>  egress {<br>    from_port   = &quot;0&quot;<br>    to_port     = &quot;0&quot;<br>    protocol    = &quot;-1&quot;<br>    cidr_blocks = [&quot;0.0.0.0/0&quot;]<br>  }</pre><pre>  tags = {<br>    Name   = &quot;server_sg&quot;<br>  }<br>}</pre><p>This security group allows SSH from the bastion host only and inbound traffic on port 8080 from VPC CIDR blocks.</p><h4>Application Related Infrastructure</h4><p>After the primary network infrastructure is configured, it can be used to securely put other AWS resources onto this infrastructure to fulfill specific application requirements.</p><p>Examples can be the following:</p><ul><li>Creating EC2 instances for various applications or databases within public or private subnets, and configuring security groups for instances to communicate each other or from other subnets.</li><li>Creating Elastic Load Balancer (ELB) in front of application EC2 instances within public or private subnets to distribute traffic. We can configure HTTPS listeners to use SSL protocol to establish secure connection from outside, and set up health checks on ELB to stop sending traffic to unhealthy EC2 instances. We can also get an SSL certificate with AWS Certificate Manager (ACM) and use it to configure HTTPS listener.</li><li>Creating an A record in the Route 53 service to point to the load balancer full qualified domain name (FQDN). This allow us to access our application with a friendly domain name.</li><li>Creating Auto Scaling Group (ASG) for a pool of same EC2 instances to prevent a single point of failure in cases of instance crashes or overloaded. We will need to first create launch configuration with security groups configured. We can leverage user-data to execute specific tasks at boot time, such as installation, updating patches, and starting services in the instance. We can then create ASG based on the launch configuration.</li><li>To be able to scale the number of instances within ASG dynamically, we can define scaling policies based on metrics such as CPU utilization. For example, we can define an AWS CloudWatch metric alarm based on CPU utilization, to trigger a scale-out or scale-in alarm event to add or remove instances if the specified thresholds is reached.</li></ul><p>One example primary and application infrastructure might look like the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*9Jwspmcd6HurhLE1aF5tKQ.png" /></figure><h4>Summary</h4><p>We have describe guidelines for setting up a secured primary network infrastructure by leveraging various AWS resources such as VPC, subnets, internet and NAT gateway, security groups, EC2, and so on. It will be the basis for application-specific infrastruce to extend on.</p><p>Infrastructure as code is an approach to defining infrastructure and network resources through declarative code. We use Terrform resource blocks to help us understand how to configure components of our infrastructure. The code can be reused and version controlled to avoid configuration drifts.</p><p>Network access control list (Network ACL) can be used in addition to security groups to provide defense in depth. Network ACLs act as a firewall for associated subnets, controlling both inbound and outbound traffic at the subnet level.</p><p>There are more advanced network and security related services we are not covering here, such as VPC Peering for communicating multiple VPCs, Site-to-Site VPN for connecting VPCs to private networks, Network ACL for preventing DoS attacks, VPC enpoints for connecting to AWS services, and AWS Web Application Firewall (WAF) for preventing common web application attacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=754c4c3fee2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting up a CI/CD Pipeline on GCP with Terraform]]></title>
            <link>https://genekuo.medium.com/setting-up-a-ci-cd-pipeline-on-gcp-with-terraform-539e66797072?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/539e66797072</guid>
            <category><![CDATA[deployment]]></category>
            <category><![CDATA[google-cloud-platform]]></category>
            <category><![CDATA[infrastructure]]></category>
            <category><![CDATA[terraform]]></category>
            <category><![CDATA[ci-cd-pipeline]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Sun, 17 Oct 2021 15:49:19 GMT</pubDate>
            <atom:updated>2021-10-17T15:49:19.234Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OoiuFv0qNfI7FVGu" /><figcaption>Photo by <a href="https://unsplash.com/@rowanfreeman?utm_source=medium&amp;utm_medium=referral">Rowan Freeman</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>In this article, we will deploy a CI/CD pipeline as code. We will use Terraform to provision this pipeline infrastructure on Google Cloud Platform (GCP). Teams that work with automated CI/CD pipelines are more agile, deploy code changes more quickly and have the benefits of improving software quality continuously.</blockquote><h4>Continuous Integration (CI) and Continous Deployment (CD)</h4><p>CI/CD pipelines generally consist of stages for building, unit/integration testing, publishing, and deploying applications on multiple environments (e.g., dev, staging, prod). However, we will focus on a single environment in this article.</p><p>The complete source code and terraform files can be found in my GitHub repository: <a href="http://pipeline/">https://github.com/genekuo/pipeline.git</a></p><h4>Prerequisites</h4><p>First, we will need to complete the following requirements on GCP for the next section related to Terraform.</p><p>Please clone the code from <a href="http://pipeline/">https://github.com/genekuo/pipeline.git</a> and change to the infrastructure directory before running the following commands. We will generate the access.json file that we will need in the the infrastructure directory.</p><ul><li>Creating a GCP project as follows</li></ul><pre>PROJECT_ID=cd-pipeline // You can define your own project<br>gcloud projects create $PROJECT_ID</pre><ul><li>Linking the billing account to the project</li></ul><pre>BILLING_ACCOUNT=$(gcloud beta billing accounts list --filter open=true --uri | awk -F / &#39;{print $NF}&#39;)</pre><pre>gcloud beta billing projects link $PROJECT_ID --billing-account $BILLING_ACCOUNT</pre><ul><li>Creating a service account in the project</li></ul><pre>SERVICE_ACCOUNT_NAME=pipeline</pre><pre>gcloud config set core/project $PROJECT_ID</pre><pre>gcloud iam service-accounts create $SERVICE_ACCOUNT_NAME</pre><ul><li>Granting a project owner IAM role to the service account</li></ul><pre>gcloud projects add-iam-policy-binding $PROJECT_ID --member serviceAccount:$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com --role roles/owner</pre><ul><li>Creating and downloading the access key for the service account</li></ul><pre>gcloud iam service-accounts keys create access.json --iam-account=$SERVICE_ACCOUNT_NAME@$PROJECT_ID.iam.gserviceaccount.com</pre><ul><li>Enabling the base services APIs</li></ul><pre>gcloud services enable cloudresourcemanager.googleapis.com serviceusage.googleapis.com</pre><h4>Services of GCP Used in The Pipeline</h4><p>We will push our source code in the one end and go through stages and tasks defined in the pipeline and finally deploy a Docker container on GCP to get feedback from users. The main services of GCP we will use as follows:</p><ul><li>Cloud Source Repository: A Git source repository for source code version control.</li><li>Cloud Build: A CI/CD service for testing, building, releasing, and deploying code.</li><li>Container Registry: A service for storing container images.</li><li>Cloud Run: A service based on Knative enables running and managing serverless workloads that automatically scale, load-balance, and resolve DNS for containers. We will use the Cloud Run service to simplify this pipeline scenario.</li></ul><h4>Parts of the Pipeline in Terraform</h4><ul><li>Variables</li></ul><p>We would like this code to be reusable, so we define some variables in variables.tf and provide values in tarraform.tfvars.</p><p>variables.tf</p><pre>variable &quot;project_id&quot; {<br>  description = &quot;The GCP project id&quot;<br>  type        = string<br>}</pre><pre>variable &quot;region&quot; {<br>  default     = &quot;us-central1&quot;<br>  description = &quot;GCP region&quot;<br>  type        = string<br>}</pre><pre>variable &quot;namespace&quot; {<br>  description = &quot;The namespace for resource naming&quot;<br>  type        = string<br>}</pre><p>terraform.tfvars</p><pre>project_id = &quot;cd-pipeline&quot;<br>namespace  = &quot;pipeline&quot;<br>region     = &quot;us-central1&quot;</pre><p>We then declare the Google provider in providers.tf and make use of variables defined above.</p><p>providers.tf</p><pre>provider &quot;google&quot; {<br>  credentials = file(&quot;access.json&quot;)<br>  project     = var.project_id<br>  region      = var.region<br>}</pre><ul><li>google_project_service</li></ul><p>We will use a Terraform resource called google_project_service to enable APIs required for constructing the pipeline. We define local variables in main.tf to define a list of services to enable and make use of for_each meta argument with the set of services in local variables to create a dynamic configuration.</p><p>main.tf</p><pre>locals {<br>  services = [<br>    &quot;sourcerepo.googleapis.com&quot;,<br>    &quot;cloudbuild.googleapis.com&quot;,<br>    &quot;run.googleapis.com&quot;,<br>    &quot;iam.googleapis.com&quot;,<br>  ]<br>}</pre><ul><li>Resource Provisioners</li></ul><p>We will use creation-time resource provisioner and destruction-time resource provisioner to coordinate the enabling of the list of services. This is to avoid the inconsistency where resources are marked “created” that they will need more time to be eventually “created” when we run terraform apply .</p><p>The following listing defines two local-exec provisioners that wait for 60 seconds after enabling each of google project services, and when destruction occurs, perform disabling each of google project services after 15 seconds.</p><p>main.tf</p><pre>resource &quot;google_project_service&quot; &quot;enabled_service&quot; {<br>  for_each = toset(local.services)<br>  project  = var.project_id<br>  service  = each.key</pre><pre>  provisioner &quot;local-exec&quot; {<br>    command = &quot;sleep 60&quot;<br>  }</pre><pre>  provisioner &quot;local-exec&quot; {<br>    when    = destroy<br>    command = &quot;sleep 15&quot;<br>  }<br>}</pre><ul><li>Pipeline</li></ul><p>For the construction of the pipeline, we will configure the following resources: google_sourcerepo_repository, google_cloudbuild_trigger, google_cloud_run_service. Those resources need to depend on the previously enabled google_project_service.</p><ul><li>google_sourcerepo_repository</li></ul><p>main.tf</p><pre>resource &quot;google_sourcerepo_repository&quot; &quot;repo&quot; {<br>  depends_on = [<br>    google_project_service.enabled_service[&quot;sourcerepo.googleapis.com&quot;]<br>  ]</pre><pre>name       = &quot;${var.namespace}-repo&quot;<br>}</pre><ul><li>google_cloudbuild_trigger</li></ul><p>We will then set up to trigger the steps of the pipeline from a push to the master branch of the source repository created by the google_sourcerepo_repository block defined previously.</p><p>These steps consist of building/testing source code, building Docker images using Dockerfile, publishing the image to the container registry, and deploying a container onto Cloud Run.</p><p>main.tf</p><pre>resource &quot;google_cloudbuild_trigger&quot; &quot;trigger&quot; {<br>  depends_on = [<br>    google_project_service.enabled_service[&quot;cloudbuild.googleapis.com&quot;]<br>  ]</pre><pre>trigger_template {<br>    branch_name = &quot;master&quot;<br>    repo_name   = google_sourcerepo_repository.repo.name<br>  }</pre><pre>build {<br>    step {<br>      name = &quot;gcr.io/cloud-builders/go&quot;<br>      args = [&quot;test&quot;]<br>      env  = [&quot;PROJECT_ROOT=${var.namespace}&quot;]<br>    }</pre><pre>step {<br>      name = &quot;gcr.io/cloud-builders/docker&quot;<br>      args = [&quot;build&quot;, &quot;-t&quot;, local.image, &quot;.&quot;]<br>    }</pre><pre>step {<br>      name = &quot;gcr.io/cloud-builders/docker&quot;<br>      args = [&quot;push&quot;, local.image]<br>    }</pre><pre>step {<br>      name = &quot;gcr.io/cloud-builders/gcloud&quot;<br>      args = [&quot;run&quot;, &quot;deploy&quot;, google_cloud_run_service.service.name, &quot;--image&quot;, local.image, &quot;--region&quot;, var.region, &quot;--platform&quot;, &quot;managed&quot;, &quot;-q&quot;]<br>    }<br>  }<br>}</pre><ul><li>google_project_iam_member</li></ul><p>We will need to give the Cloud Build service account the run.admin and iam.serviceAccountUser roles to allow Cloud Build to deploy services on Cloud Run after google_cloudbuild_trigger is created.</p><p>main.tf</p><pre>resource &quot;google_project_iam_member&quot; &quot;cloudbuild_roles&quot; {<br>  depends_on = [google_cloudbuild_trigger.trigger]<br>  for_each   = toset([&quot;roles/run.admin&quot;, &quot;roles/iam.serviceAccountUser&quot;])<br>  project    = var.project_id<br>  role       = each.key<br>  member     = &quot;serviceAccount:${<a href="/service/mailto:data.google_project.project.number}&lt;a href=">@cloudbuild</a>.gserviceaccount.com&quot;&gt;data.google_project.project.number}<a href="http://twitter.com/cloudbuild">@cloudbuild</a>.gserviceaccount.com&quot;<br>}</pre><ul><li>google_cloud_run_service</li></ul><p>We will configure the Cloud Run service and specify an default hello image to run as a container and prevent the error when running terraform apply later since we have have a image yet.</p><p>main.tf</p><pre>resource &quot;google_cloud_run_service&quot; &quot;service&quot; {<br>  depends_on = [<br>    google_project_service.enabled_service[&quot;run.googleapis.com&quot;]<br>  ]<br>  name     = var.namespace<br>  location = var.region</pre><pre>template {<br>    spec {<br>      containers {<br>        image = &quot;us-docker.pkg.dev/cloudrun/container/hello&quot;<br>      }<br>    }<br>  }<br>}</pre><ul><li>google_cloud_run_service_iam_policy</li></ul><p>To enable user access to the web service after the pipeline deploys a container on the Cloud Run service, we will define an IAM policy that grants all users the run.invoker role and attach to the Cloud Run service created previously.</p><pre>data &quot;google_iam_policy&quot; &quot;admin&quot; {<br>  binding {<br>    role = &quot;roles/run.invoker&quot;<br>    members = [<br>      &quot;allUsers&quot;,<br>    ]<br>  }<br>}</pre><pre>resource &quot;google_cloud_run_service_iam_policy&quot; &quot;policy&quot; {<br>  location    = var.region<br>  project     = var.project_id<br>  service     = google_cloud_run_service.service.name<br>  policy_data = data.google_iam_policy.admin.policy_data<br>}</pre><ul><li>Output</li></ul><p>We will finally need to output the URLs from the source repository and Cloud run service. The URLs will be used later when we demonstrate how we interact with the source repository with code changes that trigger the pipeline steps and also allow us to access the deployed web service.</p><p>outputs.tf</p><pre>output &quot;urls&quot; {<br>  value = {<br>    repo = google_sourcerepo_repository.repo.url<br>    app  = google_cloud_run_service.service.status[0].url<br>  }<br>}</pre><h4>Deploying the CI/CD Pipeline</h4><p>After we define the infrastructure for the pipeline in main.tf , we can run the following Terraform commands from the infrastructure directory to build the pipeline on GCP.</p><pre>terraform init</pre><pre>terraform plan</pre><pre>terraform apply -auto-approve</pre><h4>CI/CD in Action</h4><p>The sample source code we are using is in the service directory which contains main.go, main_test.go, Dockerfile, go.mod and go.sum. It is a simple greeting web service that responds “Hello World!” when we use curl commands with the urls.app attribute from outputs.tf previously.</p><p>We will trigger and run our CI/CD pipeline set up earlier in the event of source code changes and verify the web service deployed on the Cloud Run service.</p><p>From the service directory, we will run the following Git commands to initiate the CI/CD pipeline for the first time.</p><pre>git init</pre><pre>git add -A</pre><pre>git commit -m &quot;initial commit&quot;</pre><pre>git config --global credential.<a href="https://source.developers.google.com.helper/">https://source.developers.google.com.helper</a> gcloud.sh</pre><pre>git remote add google &lt;value from urls.repo attribute from outputs.tf previously&gt;</pre><pre>gcloud auth login</pre><pre>git push --all google</pre><p>When the pipeline completes, you can use the following command with the application URL (from the urls.app output attribute defined in outputs.tf) to verify the CI/CD scenario is successful.</p><p>We can now go to Cloud Build Dashboard on the GCP console to view the build result from our pipeline and click to view Build History and see more detailed results from each step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NDeeUqSTgXBZjcQCmYhylA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHcwxw20KaWkPF-23X8rZw.png" /></figure><h4>Summary</h4><p>We can design the CI/CD pipeline infrastructure using features of Terraform, such as Resource Providers, Resource Provisioner, and Terraform HCL.</p><p>We also make use of several GCP services such as Google Source Repository, Cloud Build, and Cloud Run with Google IAM policy and permissions to automate the CI/CD pipeline and run the application as a container.</p><p>There might be more advanced CI/CD pipelines that will meet more requirements and more sophisticated scenarios. This will serve as a basic CI/CD pipeline to be extended further.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=539e66797072" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Concurrent Programming in Go]]></title>
            <link>https://genekuo.medium.com/concurrent-programming-in-go-ad2608d3f794?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ad2608d3f794</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[concurrency]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Fri, 15 Oct 2021 06:45:31 GMT</pubDate>
            <atom:updated>2021-10-15T06:45:31.229Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*-70O9fDbUpLB8V0-" /><figcaption>Photo by <a href="https://unsplash.com/@rockthechaos?utm_source=medium&amp;utm_medium=referral">Kolleen Gladden</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>The ability to doing many things at once on the computer is called concurrency. Any Go code can be run concurrently by starting it in a Goroutine. The article will introduce some common usages, like Goroutine, WaitGroup, Channel, and Mutex, with examples. There are more advanced techniques in concurrency in Go, which we can research further and outside of this article.</blockquote><h4>Goroutines</h4><p>When we run our program and create a new Goroutine, we are running two goroutines: the main one and the one we just created. The operations in different goroutines may run in any order. In the following listing, we use time.Sleep to wait for the created Goroutines to complete their work. However, this is not an elegant solution since we don’t how long we have to wait for others to complete and it is also inefficient.</p><pre>package main</pre><pre>import (<br>  &quot;fmt&quot;<br>  &quot;time&quot;<br>)</pre><pre>func work(id int) {<br>  time.Sleep(3 * time.Second)<br>  fmt.Println(&quot;work: &quot;, id, &quot; is finished&quot;)<br>}</pre><pre>func main() {<br>  for i := 0; i &lt; 5; i++ {<br>    go work(i)<br>  }<br>  time.Sleep(4 * time.Second)<br>}</pre><h4>WaitGroup</h4><p>We can use the sync.WaitGroup function to synchronize these two Goroutines. We add a parameter called wg with a pointer to the sync.WaitGroup to the work function. When the operation in the work function is finished, we tell WaitGroup that this Goroutine is completed and we return.</p><p>Before we create a Goroutine in the main function, we tell WaitGroup to add one to its count to notify the WaitGroup that one Goroutine is running. We then call wg.Wait() for all Goroutines to finish.</p><pre>package main</pre><pre>import (<br>  &quot;log&quot;<br>  &quot;sync&quot;<br>  &quot;time&quot;<br>)</pre><pre>func work(id int, wg *sync.WaitGroup) {<br>  time.Sleep(3 * time.Second)<br>  log.Println(&quot;work: &quot;, id, &quot; is finished&quot;)<br>  wg.Done()<br>  return<br>}</pre><pre>func main() {<br>  wg := &amp;sync.WaitGroup{}<br>  for i := 0; i &lt; 5; i++ {<br>    wg.Add(1)<br>    go work(i, wg)<br>  }<br>  wg.Wait()<br>}</pre><h4>Channels</h4><p>Goroutines use channels for communication and coordination. Channels can be used as variables, as parameters passed to functions, stored in a structure, and so on. When we send values on a channel in a Goroutine, the send operation will wait until another Goroutine tries to receive on the same channel and the sender Goroutine can’t do anything. Similarly, a receiver in a Goroutine will wait until another Goroutine tries to send on the same channel. So we can modify the previous listing to use a channel to communicate with the main Goroutine that works in other Goroutines is completed.</p><pre>func work(id int, c chan int) {<br>  time.Sleep(3 * time.Second)<br>  log.Println(&quot;work: &quot;, id, &quot; is completed&quot;)<br>  c &lt;- id<br>}</pre><pre>func main() {<br>  c := make(chan int)<br>  for i := 0; i &lt; 5; i++ {<br>    go work(i, c)<br>  }</pre><pre>  for i := 0; i &lt; 5; i++ {<br>    id := &lt;- c<br>    log.Println(&quot;work: &quot;, id, &quot; has finished&quot;)<br>  }<br>}</pre><p>We can also imagine that the receive operation &lt;- c can represent the result from all Goroutines running concurrently.</p><pre>func work(in chan int, out chan int) {<br>  input := &lt;-in<br>  log.Println(&quot;input: &quot;, input)<br>  time.Sleep(3 * time.Second) // perform calculation<br>  out &lt;- input<br>}</pre><pre>func main() {<br>  in := make(chan int)<br>  out := make(chan int)</pre><pre>  var res int</pre><pre>  // Start goroutines and wait for input<br>  for i := 0; i &lt; 5; i++ {<br>    go work(in, out)<br>  }</pre><pre>  // Send input to in channel<br>  for i := 0; i &lt; 5; i++ {<br>    in &lt;- i<br>  }<br> <br>  // Collect result from out channel<br>  for i := 0; i &lt; 5; i++ {<br>    output := &lt;-out<br>    res += output<br>  }<br>  log.Println(&quot;result: &quot;, res)<br>}</pre><p>By using the concept of sending and receiving values on channels, we can design a pipeline where each Goroutine can do simple work and send its result to the next Gouroutine to produce sophisticated results eventually.</p><p>A pipeline is useful for processing large streams of data without using a large amount of memory and helps solve complex problems.</p><p>In the following listing, we use close to close a channel to signify there are no more values to be sent. And we have to check whether a channel is closed on the receiving side before reading from the channel to avoid looping forever.</p><p>v, ok := &lt;- c</p><p>We can instead use range on a channel when we are reading values from the channel until the channel is closed. The mechanism will check if a channel is closed for us.</p><p>As for the last Goroutine, we call it on the main Gouroutine to wait for other Goroutines finished and no values expected. Finally, the main Goroutine exits.</p><pre>func source(next chan string) {<br>  for _, v := range []string{&quot;apple&quot;, &quot;stone&quot;, &quot;orange&quot;, &quot;grape&quot;} {<br>    next &lt;- v<br>  }<br>  close(next)<br>}</pre><pre>func filter(in chan string, next chan string) {<br>  for v := range in {<br>    if !strings.Contains(v, &quot;stone&quot;) {<br>      next &lt;- v<br>    }<br>  }<br>  close(next)<br>}</pre><pre>func produce(in chan string) {<br>  for v := range in {<br>    log.Println(v)<br>  }<br>}</pre><pre>func main() {<br>  c0 := make(chan string)<br>  c1 := make(chan string)</pre><pre>  go source(c0)<br>  go filter(c0, c1)<br>  produce(c1)<br>}</pre><h4>Shared Values</h4><p>Sometimes, we have to deal with shared value or state among running Goroutines. If two Goroutines read and write the shared values at the same time. You might get undefined behavior or result in a race condition where the goroutines are racing to use the value.</p><p>Goroutines can mutually exclude each other from using a shared value at the same time. The feature is called Mutex from the sync package. Mutexes provide Lock and UnLock methods. If a Goroutine trying to call Lock on a locked mutex, it will wait until it is unlocked before locking it again.</p><p>The pattern to use the mutex is to make sure that any code accessing the shared values locks the mutex, uses the values, then unlocks the mutex using defer statement.</p><pre>type Counter struct {<br>  sync.Mutex<br>  count map[string]int<br>}</pre><pre>func (c *Counter) enter(name string) {<br>  c.Lock()</pre><pre>  defer c.Unlock()</pre><pre>  c.count[name]++<br>}</pre><pre>func main() {<br>  c := &amp;Counter{count: make(map[string]int)}</pre><pre>  go c.enter(&quot;apple&quot;)<br>  go c.enter(&quot;orange&quot;)<br>  go c.enter(&quot;grape&quot;)<br>  go c.enter(&quot;apple&quot;)<br>  go c.enter(&quot;stone&quot;)</pre><pre>  // Wait for the goroutines to finish<br>  time.Sleep(300 *   time.Millisecond)<br>  fmt.Println(c.count)<br>}</pre><p>We have to be careful when we use mutex to guard the shared value. We should do simple operations when the mutex is locked since we may be blocking others out for a long time. If we try to lock the same mutex without unlocking it, the lock will block forever and cause deadlock.</p><h4>Summary</h4><p>It is simple to create Goroutines to do concurrent work for us efficiently. We can use WaitGroup to wait, synchronize multiple Goroutines, and collect results from them. This also can be done preferably using channels in Go.</p><p>Channels can be used to communicate among Goroutines by sending and receiving values on them. Channels can be used to chain Goroutines together to form the streaming pipelines to simplify complex operations and leverage concurrency.</p><p>We can safeguard our shared data when multiple Goroutines try to modify the data at the same time using Mutex provided by the sync package. We can avoid deadlocks and race conditions when we use this mechanism in the right way: Locking the simple operation on the shared data and using only one Mutex for the shared data, and unlocking the Mutex when done with the shared data.</p><p>There are more advanced techniques regarding concurrency and efficiency in Go to use. I will further extend those concepts and techniques in further articles.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ad2608d3f794" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Composition with structures and method forwarding in Go]]></title>
            <link>https://genekuo.medium.com/composition-with-structures-and-method-forwarding-in-go-9a9045f2c1fd?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a9045f2c1fd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-design]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Tue, 12 Oct 2021 09:07:07 GMT</pubDate>
            <atom:updated>2021-10-12T09:07:07.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JWydJWtvIQvUuPGh" /><figcaption>Photo by <a href="https://unsplash.com/@finnfinnish?utm_source=medium&amp;utm_medium=referral">Finn Gerkens</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><blockquote>In object-oriented programming, we compose objects from smaller objects to model the problem at hand. In the same way, in Go, we use <em>composition</em> with structures. In this article, I will talk about a language feature called structure <em>embedding</em> of Go and some careful considerations, when we apply composition with structures.</blockquote><h4>Designing software with composition</h4><p>Composition is considered more flexible, greater reuse, and easier changes than software built with inheritance. We design software by breaking large structures into smaller structures and composing them together. Those smaller can be independently used and composed in many other ways, hence enhancing flexibility.</p><p>For example, a solution to compose a simple report in Go can be model as follows:</p><pre>type celsius float64</pre><pre>type temperature struct {<br>    maximum, minimum celsius<br>}</pre><pre>type location struct {<br>    latitude, longitude float64<br>}</pre><pre>type report struct {<br>    sol int<br>    temperature temperature<br>    location location<br>} </pre><p>We can then build a report as follows:</p><pre>loc := location{-41.7856, 120.5623}<br>temp := temperature{maximum: 35.0, minimum: 12.0}<br>report := report{sol: 30, temperature: temp, location: loc}</pre><pre>fmt.Printf(&quot;The maximum temperature is %v° C\n&quot;, report.temperature.maximum)</pre><p>With those types defined, we can further attach methods to each type and use them independently.</p><pre>func (t temperature) average() celsius {<br>    return (t.maximum + t.minimum) / 2<br>}</pre><pre>// Use the method independently<br>fmt.Printf(&quot;Average temperature is %v° C\n&quot;, temp.average())</pre><pre>// Or use the method from the report<br>fmt.Printf(&quot;Average temperature in the report is %v° C\n&quot;, report.temperature.average())</pre><h4>Method forwarding</h4><p>In Go, when we design software using composition, we can <em>manually</em> write methods to forward from one type to another as follows:</p><pre>func (r report) average() celsius {<br>    return r.temperature.average()<br>}</pre><pre>// Use it through the report<br>fmt.Printf(&quot;Average temperature in the report is %v° C\n&quot;, report.average())</pre><p>However, Go provides <em>method forwarding</em> for you with <em>struct embedding</em> to reduce the repetitive code we have to write. We just need to embed a type in a structure <em>without specifying a field name in that structure.</em></p><pre>type report struct {<br>    sol int<br>    temerature<br>    location<br>}</pre><p>Even though we don’t give a name for the embedded field, Go automatically gives the field name the same as the type of the structure. So we can access the field and its methods as follows:</p><pre>fmt.Printf(&quot;Average temperature in the report is %v° C\n&quot;, report.temperature.average())</pre><p>More importantly, Go allows fields of an inner structure accessible from the outer structure, and we can <em>call the methods of those fields from the outer structure.</em></p><pre>fmt.Printf(&quot;The maximum temperature is %v° C\n&quot;, report.maximum)<br>report.minimum = 10</pre><p>Any type can be embedded in structure in Go, including alias types like sol .</p><h4>Naming Collisions</h4><p>If both temperature and location fields have the same methods such as display(), we have an <em>ambiguous selector</em> when we call report.display() .</p><pre>func (t temperature) display() string {<br>    return fmt.Sprintf(&quot;Maximum temperature: %v° C, Minimum   temperature: %v° C\n&quot;, t.maximum, t.minimum)<br>}</pre><pre>func (l location) display() string {<br>    return fmt.Sprintf(&quot;logitude: %v, latitude: %v\n&quot;, l.latitude, l.longitude)<br>}</pre><pre>// call report.display() will cause error: ambiguous selector <br>// report.display<br>fmt.Printf(&quot;Disply report: %v\n&quot;, report.display())</pre><p>To resolve an <em>ambiguous selector</em>, we can implement the display method on the report type, and it will take precedence over the same method from the embedded types.</p><pre>func (r report) display() string {<br>    return fmt.Sprintf(&quot;Maximum temperature: %v° C, <br>    Minimum temperature: %v° C at <br>    (latitude: %v, latitude: %v)\n&quot;, r.maximum, r.minimum,<br>    r.latitude, r.longitude)<br>}</pre><h4>Careful considerations about embedding fields</h4><p>Because embedded fields are used to promote the fields and methods of the inner structure, the outer structure <em>implicitly satisfies the interfaces that the inner structure implements</em>. When the outer structure is used in a function or method such as parameter passing, the function or method will forward to the implementation of the inner structure. This might result in incorrect behavior that the function or method performed. The following illustrates this point.</p><pre>package main</pre><pre>import (<br> &quot;fmt&quot;<br> &quot;encoding/json&quot;<br> &quot;time&quot;<br> &quot;os&quot;<br>)</pre><pre>type Event struct {<br>    ID int<br>    time.Time<br>}</pre><pre>func main() {<br>    event := Event{<br>        ID: 6735,<br>        Time: time.Now(),<br>    }</pre><pre>second := event.Second()<br>    fmt.Printf(&quot;second: %d\n&quot;, second)</pre><pre>b, err := json.Marshal(event)<br>    if err != nil {<br>       os.Exit(1)<br>    }<br>    fmt.Printf(&quot;json: %s\n&quot;, string(b)) <br>}</pre><p>The result shows that event being marshaled doesn’t include the value of the ID field, which is not what we expect.</p><p>The reason is as follows. Through structure embedding, we promote the time.Time fields and methods to the Event structure. time.Time implements json.Marshaler interface and provide the required MarshalJSON method implementation to override the default marshaling. Now, Event also implicitly satisfies the json.Marshaler interface. When we pass event to json.Marshal, the method implementation will not use the default behavior but the one provided by the time.Time through <em>method forwarding</em>. So only time.Time filed is marshaled.</p><pre>// type declaration in package encoding/json<br>type Marshaler interface {<br>	MarshalJSON() ([]byte, error)<br>}</pre><p>One solution is to <em>provide a custom implementation of the interface promoted</em> in the outer structure to override the implementation of the same interface of the inner structure. The other solution is to not embed the field for the inner structure.</p><pre>type Event struct {<br>    ID   int<br>    Time time.Time<br>}</pre><h4>Summary</h4><p>Classical languages like Java, C#, and Python can use <em>composition</em> and <em>inheritance</em> to design software. However, <em>there isn’t inheritance in Go</em>.</p><p>Structure embedding in Go looks like inheritance in classical languages, but it is not. <em>It is about structure composition and method forwarding at work</em>.</p><p>Structure embedding provides convenience for writing software in Go and making use of composition. <em>It helps reduce boilerplate code and enhance flexibility</em>.</p><p>We must consider carefully when we design our program using composition and structure embedding, <em>with the structures we defined and those from third parties to avoid unexpected behavior</em>.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a9045f2c1fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developing A REST Service with Quarkus and Deploying to Minikube]]></title>
            <link>https://genekuo.medium.com/developing-a-rest-service-with-quarkus-and-deploying-to-minikube-c956b9ac900f?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/c956b9ac900f</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[quarkus]]></category>
            <category><![CDATA[rest-api]]></category>
            <category><![CDATA[kubernetes]]></category>
            <category><![CDATA[microservices]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Wed, 26 May 2021 16:49:54 GMT</pubDate>
            <atom:updated>2021-05-26T16:49:54.050Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tCmxxYWF1cPQ5uvh" /><figcaption>Photo by <a href="https://unsplash.com/@schmaendels?utm_source=medium&amp;utm_medium=referral">Andreas Klassen</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>We, as software developers, are now designing more microservices than monolith applications. We also need to implement microservices more productively and reliably than before, with the technology stacks we are most familiar with.</p><p>In the Java world, to develop and deploy microservices, we often utilize existing frameworks that share environments such as application servers, non-optimized Java runtimes, dynamic and reflection and so on. These result in high RAM utilization and slow startup time, further reduce developers’ productivity and microservices’ stability.</p><p>Quarkus is a Java runtime that targets the needs of the Java microservices developers. It is designed for developers to be as productive as other technology stacks such as Node.js and can be optimized to utilize as few resources as possible.</p><p>Quarkus offers features like Live Coding, annotations, plugins and patterns to increase developers’ productivity, compilation to native binary for fast startup time and low memory usage, and straightforward deployment to various Kubernetes container orchestration platforms.</p><p>We also need to make sure that we can consistently apply to microservices the capabilities such as configurations, health checking, resilience, security, reactive and streaming, metrics and tracing , and so on. Quarkus implements <a href="https://microprofile.io/">Eclipse MicroProfile Platform specifications</a> for microservices and offers those features for us to improve our productivity and microservices runtime efficiency.</p><p>This article will serve as our starting point to explore Quarkus’s features by creating a simple restful service and will cover the followings:</p><ul><li>Creating the project with the Quarkus Maven plugin and dependencies.</li><li>Developing a simple REST service endpoint with Quarkus and Live Coding mechanism.</li><li>Writing tests for the service.</li><li>Deploying the service to Kubernetes (Minikube) and see it running.</li></ul><p>The sample can be found at <a href="https://github.com/genekuo/customer-service.git">https://github.com/genekuo/customer-service.git</a> .</p><h4>Creating the project with the Quarkus Maven plugin and dependencies</h4><p>First, we will use the Quarkus Maven plugin to create our project, which is a service implementing CRUD functionalities in memory and exposing REST APIs.</p><pre>mvn io.quarkus:quarkus-maven-plugin:1.13.1.Final:create \<br>  -DprojectGroupId=demo.quarkus.service.customer \<br>  -DprojectArtifactId=customer-service \<br>  -DclassName=&quot;demo.quarkus.service.customer.CustomerEndpoint&quot; \<br>  -Dpath=&quot;/customers&quot;</pre><p>The following directory structure will be generated and major files be described below:</p><ul><li>A project object model (pom.xml) that describes the project configuration.</li><li>A JAX-RS resource endpoint named CustomerEndpoint.java and a test class named CustomerEndpointTest.java, as well as NativeCustomerEndpointIT.java for testing against the native executable.</li><li>A file named application.properties for application configuration.</li><li>An index.html file to serve as the initial static content.</li><li>A couple of Dockerfiles that allow us to create containers for our application.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/982/1*tPFnmYprWGoC1WOCmXUHDg.png" /></figure><p>We can see that there is a dependency, quarkus-resteasy, in the pom.xml, which allows us to develop and expose REST APIs. It is an implementation of the JAX-RS specification that is included by default when we create our project. We can use it to provide a representation of our service through the standard HTTP methods. We also manually include the quarkus-jsonb dependency in the pom.xml in order to produce JSON content for our REST endpoints and to create JSON objects in the test class.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-resteasy&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-resteasy-jsonb&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>You can check the various goals of the Quarkus Maven plugin with the following command.</p><pre>mvn -Dplugin=io.quarkus:quarkus-maven-plugin help:describe</pre><p>We are ready to run our application with the following command to see its default behavior.</p><pre>mvn compile quarkus:dev</pre><p>The application will be compiled and executed in a few seconds. This also starts a debugger on port 5005. Now, we can request the endpoint with a tool such as curl.</p><pre>curl http://localhost:8080/customers</pre><h4>Developing a simple REST service endpoint with Quarkus and Live Coding mechanism</h4><p>While keeping our application running, we can start to develop the Customer service with Live Coding of Quarkus. Live Coding enables Java source, resources, and configuration of a running application to be updated, recompiled, and redeployed automatically, as soon as the application receives a new request. For example, refreshing the browser or issuing a new request.</p><p>Next, we will create a model class that represents a customer’s information. This is a Plain Old Java Object that will be stored in memory by the CustomerRepository class shown next.</p><pre>public class Customer {<br>    private Integer id;<br>    private String name;<br>    private String surname;<br><br>    public Integer getId() {<br>        return id;<br>    }<br><br>    public void setId(Integer id) {<br>        this.id = id;<br>    }<br><br>    public String getName() {<br>        return name;<br>    }<br><br>    public void setName(String name) {<br>        this.name = name;<br>    }<br><br>    public String getSurname() {<br>        return surname;<br>    }<br><br>    public void setSurname(String surname) {<br>        this.surname = surname;<br>    }</pre><pre>    @Override<br>    public String toString() {<br>        return &quot;Customer{&quot; +<br>                &quot;id=&#39;&quot; + id + &#39;\&#39;&#39; +<br>                &quot;, name=&#39;&quot; + name + &#39;\&#39;&#39; +<br>                &quot;, surname=&#39;&quot; + surname + &#39;\&#39;&#39; +<br>                &#39;}&#39;;<br>    }<br>}</pre><p>The CustomerRepository here represents the core CRUD (Create, Retrieve, Update and Delete) functionalities which manage our model.</p><pre>@ApplicationScoped<br>public class CustomerRepository {<br><br>    List&lt;Customer&gt; customerList = new ArrayList();<br>    int counter;<br><br>    public int getNextCustomerId() {<br>        return counter++;<br>    }<br><br>    public List&lt;Customer&gt; findAll() {<br>        return customerList;<br>    }<br><br>    public Customer findCustomerById(Integer id) {<br>        for (Customer c:customerList) {<br>            if (c.getId().equals(id))  {<br>                return c;<br>            }<br>        }<br>        throw new CustomerException(&quot;Customer not found!&quot;);<br>    }<br><br>    public void updateCustomer(Customer customer) {<br>        Customer customerToUpdate = findCustomerById(customer.getId());<br>        customerToUpdate.setName(customer.getName());<br>        customerToUpdate.setSurname(customer.getSurname());<br>    }<br><br>    public void createCustomer(Customer customer) {<br>        customer.setId(getNextCustomerId());<br>        findAll().add(customer);<br>    }<br><br>    public void deleteCustomer(Integer customerId) {<br>        Customer c = findCustomerById(customerId);<br>        findAll().remove(c);<br>    }<br>}</pre><p>Finally, we will create a REST endpoint over the CustomerRepository class and define a method for each CRUD functionality. Each method in CustomerEndpoint class is mapped to an appropriate HTTP method and exposes to clients to communicate with.</p><pre>@Path(&quot;customers&quot;)<br>@ApplicationScoped<br>public class CustomerEndpoint {<br><br>    @Inject<br>    CustomerRepository customerRepository;<br><br>    @GET<br>    @Produces(MediaType.<em>APPLICATION_JSON</em>)<br>    public List&lt;Customer&gt; getAll() {<br>        return customerRepository.findAll();<br>    }<br><br>    @GET<br>    @Path(&quot;{id}&quot;)<br>    @Produces(MediaType.<em>APPLICATION_JSON</em>)<br>    public Customer findById(@PathParam(&quot;id&quot;) Integer id) {<br>        return customerRepository.findCustomerById(id);<br>    }<br><br>    @POST<br>    @Consumes(MediaType.<em>APPLICATION_JSON</em>)<br>    @Produces(MediaType.<em>APPLICATION_JSON</em>)<br>    public Response create(Customer customer) {<br>        customerRepository.createCustomer(customer);<br>        return Response.<em>status</em>(201).build();<br>    }<br><br>    @PUT<br>    @Consumes(MediaType.<em>APPLICATION_JSON</em>)<br>    @Produces(MediaType.<em>APPLICATION_JSON</em>)<br>    public Response update(Customer customer) {<br>        customerRepository.updateCustomer(customer);<br>        return Response.<em>status</em>(204).build();<br>    }<br><br>    @DELETE<br>    public Response delete(@QueryParam(&quot;id&quot;) Integer customerId) {<br>        customerRepository.deleteCustomer(customerId);<br>        return Response.<em>status</em>(204).build();<br>    }<br>}</pre><p>While our application is still running, we can start sending requests to the CustomerEndpoints to experience Live Coding mechanism and see our application work.</p><pre>// Initially, the command will return nothing<br>curl <a href="http://localhost:8080/customers">http://localhost:8080/customers</a> </pre><pre>// We add a customer to our application<br>curl -v -X POST -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;name&quot;:&quot;Bill&quot;,&quot;surname&quot;:&quot;John&quot;}&#39; \<br>  <a href="http://localhost:8080/customers">http://localhost:8080/customers</a></pre><pre>// Now we have a customer record<br>curl <a href="http://localhost:8080/customers">http://localhost:8080/customers</a></pre><pre>// We can also find the customer by id<br>curl <a href="http://localhost:8080/customers/20">http://localhost:8080/customers/0</a></pre><pre>// Then we can update the customer details<br>curl -v -X PUT -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;id&quot;:0,&quot;name&quot;:&quot;Tom&quot;,&quot;surname&quot;:&quot;Chris&quot;}&#39; \<br>  <a href="http://localhost:8080/customers">http://localhost:8080/customers</a></pre><pre>// Finally we delete the customer record<br>curl -v -X DELETE <a href="http://localhost:8080/customers?id=22">http://localhost:8080/customers?id=</a>0</pre><h4>Writing tests for the service</h4><p>We will write a quick test for the CustomerEndpoint to verify that our code actually works. However, this simple test has not considered the best practices about unit testing or integration testing, such as grouping tests, isolation of test methods, detailed assertions and so on, which can be elaborated further in order to obtain high quality of tests. Instead, I will focus on describing the supports that Quarkus offers for testing. As we can in the pom.xml, the following dependencies has been added by default to support unit testing our service.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-junit5&lt;/artifactId&gt;<br>  &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.rest-assured&lt;/groupId&gt;<br>  &lt;artifactId&gt;rest-assured&lt;/artifactId&gt;<br>  &lt;scope&gt;test&lt;/scope&gt;<br>&lt;/dependency&gt;</pre><p>We have used Json.createObjectBuilder API to create two JSON objects and serialize to strings that are sent to our CustomerEndpoint, and to verify its functionalities.</p><pre>@QuarkusTest<br>public class CustomerEndpointTest {<br><br>    @Test<br>    public void testCustomerService() {<br><br>        JsonObject obj = Json.<em>createObjectBuilder</em>()<br>                .add(&quot;name&quot;, &quot;John&quot;)<br>                .add(&quot;surname&quot;, &quot;Smith&quot;).build();<br><br>        // Test POST<br>        <em>given</em>()<br>                .contentType(&quot;application/json&quot;)<br>                .body(obj.toString())<br>                .when()<br>                .post(&quot;/customers&quot;)<br>                .then()<br>                .statusCode(201);<br><br>        // Test GET<br>        <em>given</em>()<br>                .when().get(&quot;/customers&quot;)<br>                .then()<br>                .statusCode(200)<br>                .body(<em>containsString</em>(&quot;John&quot;),<br>                        <em>containsString</em>(&quot;Smith&quot;));<br><br>        obj = Json.<em>createObjectBuilder</em>()<br>                .add(&quot;id&quot;, 0)<br>                .add(&quot;name&quot;, &quot;Tom&quot;)<br>                .add(&quot;surname&quot;, &quot;Chris&quot;).build();<br><br>        // Test PUT<br>        <em>given</em>()<br>                .contentType(&quot;application/json&quot;)<br>                .body(obj.toString())<br>                .when()<br>                .put(&quot;/customers&quot;)<br>                .then()<br>                .statusCode(204);<br><br>        // Test DELETE<br>        <em>given</em>()<br>                .contentType(&quot;application/json&quot;)<br>                .when()<br>                .delete(&quot;/customers?id=0&quot;)<br>                .then()<br>                .statusCode(204);<br>    }<br>}</pre><p>After we have our test class in place, we can perform our tests with the following command.</p><pre>mvn clean test</pre><h4>Packaging and deploying the service to Kubernetes (Minikube)</h4><p>It is time to package and deploy our Customer Service to Kubernetes. In order to package an application for deployment to Kubernetes, we will use <a href="https://github.com/GoogleContainerTools/jib">Jib</a> dependency.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-container-image-jib&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>Next, we will need two more dependencies to create a Kubernetes manifest YAML specific for Minikube development cluster for out application.</p><pre>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-kubernetes&lt;/artifactId&gt;<br>&lt;/dependency&gt;<br>&lt;dependency&gt;<br>  &lt;groupId&gt;io.quarkus&lt;/groupId&gt;<br>  &lt;artifactId&gt;quarkus-minikube&lt;/artifactId&gt;<br>&lt;/dependency&gt;</pre><p>We can modify application.properties to specify the Docker image name and Kubernetes service name when we run mvn clean install command. The .yml and .json will be generated in /target/kubernetes as the result.</p><pre>quarkus.container-image.group=quarkus-mp<br>quarkus.container-image.name=customer-service<br>quarkus.kubernetes.name=customer-service</pre><p>After the previous setup, we are ready to package our application and deploy to Minikube. We will start the Minkube cluster and make use of the Docker daemon inside Minikube with the following commands.</p><pre>minikube start</pre><pre>eval $(minikube -p minikube docker-env)</pre><p>We can now use quarkus-container-image-jib to create an image for JVM execution and check our image.</p><pre>mvn clean package -Dquarkus.container-image.build=true</pre><pre>docker images // will show quarkus-mp/customer-service image created</pre><p>Finally, we can deploy our application to Minikube and test it with the following command.</p><pre>mvn clean package -Dquarkus.kubernetes.deploy=true</pre><p>The above command will generate the necessary container and deploy to the Kubernetes cluster specified in the /[HOME]/.kube/config.</p><p>We can now query our service URL exposed by Minikube and test it.</p><pre>minikube service list<br></pre><pre>// Initially, the command will return nothing<br>curl <a href="http://localhost:8080/customers">http://[URL]/customers</a></pre><pre>// We add a customer to our application<br>curl -v -X POST -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;name&quot;:&quot;Bill&quot;,&quot;surname&quot;:&quot;John&quot;}&#39; \<br>  <a href="http://localhost:8080/customers">http://[URL]/customers</a></pre><pre>// Now we have a customer record<br>curl <a href="http://localhost:8080/customers">http://[URL]/customers</a></pre><pre>// We can also find the customer by id<br>curl <a href="http://localhost:8080/customers/20">http://[URL]/customers/0</a></pre><pre>// Then we can update the customer details<br>curl -v -X PUT -H &quot;Content-Type: application/json&quot; \<br>  -d &#39;{&quot;id&quot;:0,&quot;name&quot;:&quot;Tom&quot;,&quot;surname&quot;:&quot;Chris&quot;}&#39; \<br>  <a href="http://localhost:8080/customers">http://[URL]/customers</a></pre><pre>// Finally we delete the customer record<br>curl -v -X DELETE <a href="http://localhost:8080/customers?id=22">http://[URL]/customers?id=</a>0</pre><h4>Summary</h4><p>In this article, we went through our first Quarkus application, implemented a REST service, tested it and deployed to a single node Kubernetes cluster. We learned how to create a JAX-RS resource, use CDI Scope annotation @ApplicationScoped on the JAX-RS resource class and the Repository class. We know how to use @Inject annotation to inject the dependent CDI bean.</p><p>We also know that rest-assured and the Quarkus JUnit extension can be used to create quality tests before packaging an application and deployment.</p><p>We demonstrated how to develop an application with Quarkus Live Coding, packaged our application with the quarkus-container-image-jib dependency, generated manifest YAML files for Kubernetes cluster and for Minikube cluster specifically. Using these Quarkus extensions, we can go from application development, to testing, and to packaging and deployment, without any other tooling. These all make our application development much more productive.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c956b9ac900f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a REST API in Rust with Persistence: Rust, Rocket and Diesel]]></title>
            <link>https://genekuo.medium.com/creating-a-rest-api-in-rust-with-persistence-rust-rocket-and-diesel-a4117d400104?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4117d400104</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rockets]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Tue, 02 Feb 2021 16:20:21 GMT</pubDate>
            <atom:updated>2021-02-02T16:20:21.938Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7s6xT3YqZKGr4mZd" /><figcaption>Photo by <a href="https://unsplash.com/@jlondonbaker?utm_source=medium&amp;utm_medium=referral">John Baker</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>We will be creating a REST API in Rust, which serves resources (posts) with persistence in a postgres database.</p><p>Rocket framework will be used to setup the API and Diesel to handle persistence with a Postgres database.</p><p>We will test our Rust API and a Postgres database by running them as separate docker containers which communicate with each other to expose CRUD functionalities from our API and implement persistence with a Postgres database.</p><p>I’ve provided the source code in the rocket-diesel branch of my Github repo.</p><p><a href="https://github.com/genekuo/rust-microservices/tree/rocket-diesel">genekuo/rust-microservices</a></p><h3>Dependencies: Cargo.toml</h3><p>First, we need to setup the following dependencies for our REST API project:</p><pre>[dependencies]<br>rocket = &quot;0.4.5&quot;<br>rocket_codegen = &quot;0.4.5&quot;<br>diesel = { version = &quot;1.4.4&quot;, features = [&quot;postgres&quot;] }<br>dotenv = &quot;0.15.0&quot;<br>r2d2-diesel = &quot;1.0.0&quot;<br>r2d2 = &quot;0.8.9&quot;<br>serde = &quot;1.0.116&quot;<br>serde_derive = &quot;1.0.116&quot;<br>serde_json = &quot;1.0.58&quot;<br>env_logger = &quot;0.5.12&quot;<br>log = &quot;0.4.6&quot;</pre><pre>[dependencies.rocket_contrib]<br>version = &quot;*&quot;<br>default-features = false<br>features = [&quot;json&quot;]</pre><p>Let’s focus on several important crates in the following.</p><p>rocket crate: this crate provides Rocket as a web framework for Rust with a focus on ease-of-use, expressibility, and speed. Rocket requires a nightly version of Rust as it makes heavy use of syntax extensions.</p><p>rocket_codegen: this crate allows us to use the implementation of code generation of Rocket, which includes custom derives, custom attributes, and procedural macros.</p><p>diesel: this crate provides a safe, extensible ORM and Query Builder for Rust. We specify postgres feature to include only the postgres module in the Diesel crate. If different or multiple databases are needed in our project, we can just specify them in the features list.</p><p>r2d2 and r2d2-diesel: r2d2 is a generic connection pool for Rust. r2d2-diesel provides r2d2 support to allow connection pooling with Diesel. r2d2 and r2d2-diesel are included for using the diesel crate with r2d2 pools.</p><p>serde, serde_derive, serde_json: these crates helps us to make structs serializable and deserializable with different formats, such as JSON, CBOR, MessagePack, and BSON.</p><h3>Diesel</h3><p>Diesel crate helps generating Rust types that representing tables and records in a SQL database and creating a domain-specific language to query data from a database.</p><p>At the time of writing this article, the only databases that Diesel supports are Postgres, MySql and Sqlite.</p><h4>Generating and applying migrations: up.sql and down.sql</h4><p>We will need diesel_cli to create migrations and apply them. For that, we need to use the following command to install diesel_cli.</p><pre>cargo install diesel_cli --no-default-features --features &quot;postgres&quot;</pre><p>We can then prepare the necessary migrations.</p><pre>diesel setup</pre><p>Since we are going to model posts which can be inserted, retrieved, updated and deleted from the database, we can create a migration directory containing two files: up.sql and down.sql.</p><pre>diesel migration generate create_posts</pre><p>The above command creates two new files: up.sql and down.sql in a single folder in the migrations directory. We can then modify up.sql and down.sql with the following SQL statements for upgrading and downgrading migrations in the database if necessary.</p><h4>up.sql</h4><pre>CREATE TABLE posts (<br>  id SERIAL PRIMARY KEY,<br>  title VARCHAR NOT NULL,<br>  body TEXT NOT NULL,<br>  published BOOLEAN NOT NULL DEFAULT &#39;f&#39;<br>)</pre><h4>down.sql</h4><pre>DROP TABLE posts</pre><p>We can apply all the upgrading and downgrading migrations with the following command to create the database and the posts table.</p><pre>DATABASE_URL=postgres://username:password@localhost/postgres diesel migration run</pre><p>Or, with the .env file specify DATABASE_URL environment variable, we can just run the following instead.</p><pre>diesel migration run</pre><h4>schema.rs</h4><p>We can use the following command to generate a Rust schema file which uses table! macro to implement the database mappings for us.</p><pre>diesel print-schema &gt; src/schema.rs</pre><p>schema.rs</p><pre>table! {<br>    posts (id) {<br>        id -&gt; Int4,<br>        title -&gt; Varchar,<br>        body -&gt; Text,<br>        published -&gt; Bool,<br>    }<br>}</pre><h3>Object-relational Mapping (ORM): model.rs</h3><p>After we have a posts table in a Postgres database, we can start mapping the table to structs in Rust.</p><pre>#[derive(Queryable, AsChangeset, Serialize, Deserialize, Debug)]<br>#[table_name = &quot;posts&quot;]<br>pub struct Post {<br>    pub id: i32,<br>    pub title: String,<br>    pub body: String,<br>    pub published: bool,<br>}</pre><pre>#[derive(Insertable, Serialize, Deserialize)]<br>#[table_name=&quot;posts&quot;]<br>pub struct NewPost {<br>    pub title: String,<br>    pub body: String,<br>}</pre><p>#[table_name = “posts”] on Post struct maps the struct to the table posts from the database. Therefore, an instance of the Post struct represents each record in the posts table.</p><p>The Queryable, AsChangeset attributes on Post struct instruct Diesel to generate code for retrieving posts and executing updates on posts table from the database.</p><p>The Serialize and Deserialize use serde crate to transform between instances of Post struct and JSON format between REST API requests and responses.</p><p>We also define a NewPost struct without the id field to serve the purpose of inserting a post record into the database. The id of the record will be generated automatically when inserted, and we could specify exactly the fields that can be filled during insertion.</p><p>The Insertable attribute on NewPost is used by diesel crate to generate code for inserting a new record.</p><h3>Connection Pool: connection.rs</h3><p>Before wen can make use of Diesel ORM to persist Rust struct instances in the database, we have to create a module for the connection pool and the connection request guard. The connection pool will be configured with Rocket router (router.rs) as a Rocket managed state.</p><p>DBConn connection request guard can set a policy to retrieve a PgConnection from the managed pool and then pass it to handlers (handler.rs), and subsequently pass it to repository (repository.rs) for the database querying and updating executions.</p><pre>type Pool = r2d2::Pool&lt;ConnectionManager&lt;PgConnection&gt;&gt;;</pre><pre>pub fn init_pool() -&gt; Pool {<br>  let manager = ConnectionManager::&lt;PgConnection&gt;::new(database_url());<br>    Pool::new(manager).expect(&quot;db pool&quot;)<br>}</pre><pre>fn database_url() -&gt; String {<br>    env::var(&quot;DATABASE_URL&quot;).expect(&quot;DATABASE_URL must be set&quot;)<br>}</pre><pre>pub struct DbConn(pub<br>  r2d2::PooledConnection&lt;ConnectionManager&lt;PgConnection&gt;&gt;);</pre><pre>impl&lt;&#39;a, &#39;r&gt; FromRequest&lt;&#39;a, &#39;r&gt; for DbConn {<br>    type Error = ();<br>  fn from_request(request: &amp;&#39;a Request&lt;&#39;r&gt;) -&gt;   request::Outcome&lt;DbConn, Self::Error&gt; {<br>        let pool = request.guard::&lt;State&lt;Pool&gt;&gt;()?;<br>        match pool.get() {<br>            Ok(conn) =&gt; Outcome::Success(DbConn(conn)),<br>            Err(_) =&gt; Outcome::Failure((Status::ServiceUnavailable, ())),<br>        }<br>    }<br>}</pre><pre>impl Deref for DbConn {<br>  type Target = PgConnection;<br>  fn deref(&amp;self) -&gt; &amp;Self::Target {<br>        &amp;self.0<br>    }<br>}</pre><p>Here we define an alias Pool to the type for a pool of Diesel Postgres connection.</p><p>The init_pool function will initialize the connection pool by using r2d2 and r2d2_diesel crates.</p><p>We will later configure the pooled connections in router.rs as managed state in Rocket framework.</p><p>We then define the connection request guard type DbConn which is a wrapper around an r2d2 pooled connection. According to Rocket documentation: <a href="https://api.rocket.rs/v0.4/rocket/request/trait.FromRequest.html">https://api.rocket.rs/v0.4/rocket/request/trait.FromRequest.html</a>, a request guard is a type that represents an arbitrary validation policy which is implemented through FromRequest trait. Every type that implements FromRequest is a request guard.</p><p>Therefore, we can implements FromRequest for DbConn to define a policy for the attempts to retrieve a single connection from the managed database pool.</p><p>We can define an arbitrary number of request guards to use as arguments in a route handler (handler.rs). Rocket will automatically invoke the FromRequest implementation for request guards before calling the handler. And, Rocket only dispatches requests to a handler when all its guards pass. In our case, an available connection from the pool is retrieved.</p><p>We also implements Deref trait for DbConn for the convenience of using an &amp;*PgConnection when we want to get the actual connection.</p><h3>Repository: repository.rs</h3><p>With the table created and structs mapped to it in the previous sections, we can now implement CRUD functionalities against the database in the repository module.</p><pre>#![allow(proc_macro_derive_resolution_fallback)]</pre><pre>use diesel;<br>use diesel::prelude::*;</pre><pre>use crate::sample::model::Post;<br>use crate::sample::model::NewPost;</pre><pre>use crate::schema::posts;<br>use crate::schema::posts::dsl::*;</pre><pre>pub fn create_post(new_post: NewPost, conn: &amp;PgConnection) -&gt; QueryResult&lt;Post&gt; {<br>    diesel::insert_into(posts::table)<br>        .values(&amp;new_post)<br>        .get_result(conn)<br>}</pre><pre>pub fn show_posts(connection: &amp;PgConnection) -&gt; QueryResult&lt;Vec&lt;Post&gt;&gt;  {<br>    //posts.filter(published.eq(true))<br>    posts.limit(5)<br>        .load::&lt;Post&gt;(&amp;*connection)<br>}</pre><pre>pub fn get_post(post_id: i32, connection: &amp;PgConnection) -&gt; QueryResult&lt;Post&gt; {<br>    posts::table.find(post_id).get_result::&lt;Post&gt;(connection)<br>}</pre><pre>pub fn update_post(post_id: i32, post: Post, connection: &amp;PgConnection) -&gt; QueryResult&lt;Post&gt; {<br>    diesel::update(posts::table.find(post_id))<br>        .set(&amp;post)<br>        .get_result(connection)<br>}</pre><pre>pub fn delete_post(post_id: i32, connection: &amp;PgConnection) -&gt; QueryResult&lt;usize&gt; {<br>    diesel::delete(posts::table.find(post_id))<br>        .execute(connection)<br>}</pre><p>The diesel module allow us to use various functions such as insert_into, update, and delete.</p><p>diesel::prelude::* provides access to a range of modules and structs such as PgConnection and QueryResult .</p><p>schema::posts and schema::posts::dsl::* are for access to the posts table from within Rust and for bringing in all the available Diesel DSL methods, so we can interact with the database tables.</p><p>For example, get_post allow us to access the posts table via posts::table. We can then use find function with the specified post_id and call get_result to execute the query with the provided connection.</p><p>Another examples show different usages: create_post , update_post, which we can compose diesel::insert_into or diesel::update functions with posts::table and/or its functions to execute inserting and updating a record.</p><p>QueryResult is returned from all functions we define here. It is an alias type for Result&lt;T, Error&gt; . Therefore, returning QueryResult allows us to indicate what happens if the query fails in whatever way is suitable for where the function is used.</p><h3>Rocket</h3><p>Rocket is a web framework that uses nightly compiler’s features that converts a set of Rust functions called handlers into a complete web services.</p><p>The following lines of code import macros from the crates we need to use the features of connection pooling with Diesel, data serialization and deserialization for requests and responses, handlers declaration and logging.</p><pre>#![feature(decl_macro, proc_macro_hygiene)]<br>#[macro_use]<br>extern crate diesel;<br>extern crate dotenv;<br>extern crate r2d2;<br>extern crate r2d2_diesel;<br>#[macro_use]<br>extern crate rocket;<br>extern crate rocket_contrib;<br>#[macro_use]<br>extern crate serde_derive;</pre><p>The two features from the nightly release: decl_macro, proc_macro_hygiene, allow us to declare handlers to handle requests from clients.</p><h4>Handlers: handler.rs</h4><p>A handler in Rocket is a function that takes parameter bindings, handle the mapped request and return the result in JSON format.</p><p>Each function has an attribute that specifies what REST verb of GET, POST, PUT and DELETE it accepts and the path needed to get to the function.</p><p>Each handler delegates to the repository module (repository.rs) we added here, with the database connection: PgConnection to perform queries<br>and updates on the Postgres database.</p><p>For example, the function update_post accepts an input parameter id , binding the &lt;/id&gt; from the request, then delegating to repository::update_post function to update a specific post with the same id in the database.</p><p>The &lt;/id&gt; represents the path variable id specified in the request URL. The data = “&lt;post&gt;” represents the request body that maps to post inside the function.</p><p>The contents of post is retrieved by calling post.into_inner() and pass to repository::update_post function.</p><p>If the operation is successful, it will wrap the updated post as an Json instance, which is wrapped into the Result type.</p><p>If the operation is failed, the error will be transformed into Status and wrapped into Result.</p><p>The Rocker framework will handle the result from this function to respond to the client with either successful records or a specific status code when failure.</p><pre>#[get(&quot;/&quot;)]<br>pub fn all_posts(connection: DbConn) -&gt; Result&lt;Json&lt;Vec&lt;Post&gt;&gt;, Status&gt; {<br>    sample::repository::show_posts(&amp;connection)<br>        .map(|post| Json(post))<br>        .map_err(|error| error_status(error))<br>}</pre><pre>#[post(&quot;/&quot;, format =&quot;application/json&quot;, data = &quot;&lt;new_post&gt;&quot;)]<br>pub fn create_post(new_post: Json&lt;NewPost&gt;, connection: DbConn) -&gt;  Result&lt;status::Created&lt;Json&lt;Post&gt;&gt;, Status&gt; {<br>    println!(&quot;here 0 {}&quot;,&amp;new_post.title);<br>    sample::repository::create_post(new_post.into_inner(), &amp;connection)<br>        .map(|post| post_created(post))<br>        .map_err(|error| error_status(error))</pre><pre>}</pre><pre>#[get(&quot;/&lt;id&gt;&quot;)]<br>pub fn get_post(id: i32, connection: DbConn) -&gt; Result&lt;Json&lt;Post&gt;, Status&gt; {<br>    sample::repository::get_post(id, &amp;connection)<br>        .map(|post| Json(post))<br>        .map_err(|error| error_status(error))<br>}</pre><pre>#[put(&quot;/&lt;id&gt;&quot;, format = &quot;application/json&quot;, data = &quot;&lt;post&gt;&quot;)]<br>pub fn update_post(id: i32, post: Json&lt;Post&gt;, connection: DbConn) -&gt; Result&lt;Json&lt;Post&gt;, Status&gt; {<br>    sample::repository::update_post(id, post.into_inner(), &amp;connection)<br>        .map(|post| Json(post))<br>        .map_err(|error| error_status(error))<br>}</pre><pre>#[delete(&quot;/&lt;id&gt;&quot;)]<br>pub fn delete_post(id: i32, connection: DbConn) -&gt; Result&lt;status::NoContent, Status&gt; {<br>    sample::repository::delete_post(id, &amp;connection)<br>        .map(|_| status::NoContent)<br>        .map_err(|error| error_status(error))<br>}</pre><h4>Router: router.rs</h4><p>After we setup handlers to accept requests to the server, we can then map the routes to the different functions in the handler module.</p><pre>use rocket;</pre><pre>use crate::connection;<br>use crate::sample;</pre><pre>pub fn create_routes() {<br>    rocket::ignite()<br>        .manage(connection::init_pool())<br>        .mount(&quot;/posts&quot;,<br>               routes![<br>                    sample::handler::all_posts,<br>                    sample::handler::create_post,<br>                    sample::handler::get_post,<br>                    sample::handler::update_post,<br>                    sample::handler::delete_post<br>                    ],<br>        ).launch();<br>}</pre><p>We create a Rocket instance with the ignite method. Before we launch it, we have to add state which is Pool to be managed by this instance of Rocket.</p><p>Managed state can be retrieved by any request handler via the State request guard, which is via from_request function of the DbConn .</p><p>In particular, if a value of type T is managed by Rocket, adding State&lt;T&gt; , in our case DbConn , to the list of arguments in a request handler instructs Rocket to retrieve the managed value.</p><p>Finally, we specify all of the handler functions inside of routes!macro and then start our REST server by calling launch.</p><h3>Environment variables and main function: main.rs</h3><p>In main.rs, we simply load environment variables and call router::create_routes function to start the REST server.</p><p>The environment variables we will use are:</p><p>RUST_BACKTRACE=1<br>RUST_LOG=debug<br>ROCKET_ADDRESS=0.0.0.0<br>ROCKET_PORT=8000<br>DATABASE_URL=postgres://username:password@db/postgres</p><p>Environment variables include Rust, Rocket, and database related configuration variables as the above. They can be specified in .env file or Rocket.toml file in the project’s root directory if needed.</p><p>Since we will containerize our REST services and Postgres database, we will make use of docker-compose file to specify these environment variables and inject them into containers, shown in the following section.</p><h3>Building images and Testing</h3><p>When we are in the middle of developing our REST services, we can use the following commands to run and test the services.</p><p>First, we will run a Postgres database container.</p><pre>docker run --rm --detach --name postgres --env POSTGRES_USER=username --env POSTGRES_PASSWORD=password --publish 127.0.0.1:5432:5432 postgres</pre><p>We will then install diesel-cli and run the following Diesel-related commands mentioned previously.</p><pre>diesel setup<br>diesel migration generate create_posts<br>// modify up.sql and down.sql as needed</pre><pre>diesel migration run</pre><p>After coding ORM, repository, handlers and routers, we run cargo run to start the services and use curl to test them.</p><pre>cargo run</pre><pre>curl -d &#39;{&quot;title&quot;: &quot;Rust microservices&quot;, &quot;body&quot;: &quot;Using Diesel to implement persistence&quot;}&#39; -H &quot;Content-Type: application/json&quot; -X POST <a href="http://localhost:8000/posts">http://localhost:8000/posts</a></pre><pre>curl <a href="http://localhost:8000/posts">http://localhost:8000/posts</a></pre><p>We also provide a Dockerfile in my GitHub repo for two-stage containers build to create a build image (for compilation) and a runtime image to reduce the size of the runtime image.</p><p>Also, we use a docker-compose.yml to run our REST services from the runtime image and Postgres database from postgres:latest image, capture the environment configurations and link them to simulate a simple microservices deployment in our local development.</p><p>Finally, we can confirm the functionalities of our REST services and persistence using the following commands.</p><pre>docker-compose up -d</pre><pre>diesel migration run</pre><pre>curl -d &#39;{&quot;title&quot;: &quot;Rust microservices&quot;, &quot;body&quot;: &quot;Using Diesel to implement persistence&quot;}&#39; -H &quot;Content-Type: application/json&quot; -X POST <a href="http://localhost:8000/posts">http://localhost:8000/posts</a></pre><pre>curl -d &#39;{&quot;title&quot;: &quot;Rust microservices&quot;, &quot;body&quot;: &quot;Using Rocket to build a API&quot;}&#39; -H &quot;Content-Type: application/json&quot; -X POST <a href="http://localhost:8000/posts">http://localhost:8000/posts</a></pre><pre>curl <a href="http://localhost:8000/posts/1">http://localhost:8000/posts/1</a></pre><pre>curl -d &#39;{&quot;id&quot;:1, &quot;title&quot;: &quot;Rust microservices&quot;, &quot;body&quot;: &quot;Using Diesel and Rocket to build microservices&quot;, &quot;published&quot;: true}&#39; -H &quot;Content-Type: application/json&quot; -X PUT <a href="http://localhost:8000/posts/1">http://localhost:8000/posts/1</a></pre><pre>curl -X DELETE <a href="http://localhost:8000/posts/2">http://localhost:8000/posts/2</a></pre><pre>curl <a href="http://localhost:8000/posts">http://localhost:8000/posts</a></pre><pre>docker-compose down</pre><h3>Conclusions</h3><p>Combining Rocket web framework and Diesel ORM in Rust can be a powerful way to create a REST API with persistence on a SQL database.</p><p>The Rocket framework allows us to write request handlers in an intuitive and clear style with the help of the nightly Rust compiler.</p><p>Interaction to databases with Diesel object-relation mapping features, its generated domain-specific language and composable abstractions simplify our Rust code for complex queries.</p><p>We can further explore their features and usages to create more production-grade applications or APIs, such API security, complex queries with multiple tables or schemas, applying more microservices patterns and so on.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4117d400104" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coding a simple microservices with Rust]]></title>
            <link>https://genekuo.medium.com/coding-a-simple-microservices-with-rust-3fbde8e32adc?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3fbde8e32adc</guid>
            <category><![CDATA[containers]]></category>
            <category><![CDATA[rust]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[restful]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Sun, 06 Dec 2020 07:32:00 GMT</pubDate>
            <atom:updated>2020-12-06T07:32:00.655Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*xUSZDSrvIaUFxBa7surCmg.png" /></figure><h4>Introduction</h4><p>We will create a simple REST service providing the functions of CRUD (create, read, update, and delete) for in-memory user data. Without serialization and deserialization between JSON and Rust instances, which we will expand the source code on further articles, this example will handle only CRUD of user ids to focus on the coding of a HTTP service with Rust and relevant crates.</p><p>The sample code can be cloned from the following GitHub repository: <a href="https://github.com/genekuo/rust-microservices.git">https://github.com/genekuo/rust-microservices.git</a></p><p>After implementing the initial version of the microservices, we will test it by using curl commands to see how it works.</p><h4>Initial setup with hyper crate</h4><p>We have decided to make use of Rust’s hyper crate to build a server to handle HTTP requests and responses. hyper crate is built on top of the futures crate and uses tokio crate for the server runtime.</p><p>First, we will use the following command to make a new project:</p><p>cargo new rust-microservices</p><p>Within the created folder, we then add the following dependencies to the Cargo.toml file.</p><pre>[dependencies]<br>hyper = &quot;0.12&quot;<br>futures = &quot;0.1&quot;</pre><p>In the main function, we will do the following setup to function as a simple HTTP server:</p><p>We will create the SocketAddr from a tuple of the ([u8; 4], u16) and bind to it. This is hardcoded for now. Normally, SocketAddr should be created from external strings, like command-line arguments or environment variables.</p><pre>let addr = ([0, 0, 0, 0], 8080).into();<br>let builder = Server::bind(&amp;addr);</pre><p>Before addingNewService to the builderto handle requests, we will define the data for the microservices. Then, we can pass it to the handler function when we create a NewService .</p><h4>Guard the data among multiple threads</h4><p>The data may be used by many handlers even though we will have only one handler making use of the data in this article. Therefore, we have to use an atomic reference counter Arcand mutual exclusive primitive Mutexfor protecting this shared data used with multiple threads.</p><p>We also use Slab to provide the pre-allocated storage for the data. It won’t resize if we remove the item from the underlining data.</p><pre>type UserId = u64;</pre><pre>struct UserData;</pre><pre>impl fmt::Display for UserData {<br>    fn fmt(&amp;self, f: &amp;mut fmt::Formatter) -&gt; fmt::Result {<br>        f.write_str(&quot;{}&quot;)<br>    }<br>}</pre><pre>type UserDb = Arc&lt;Mutex&lt;Slab&lt;UserData&gt;&gt;&gt;;</pre><p>The dependencies will then becomes:</p><pre>[dependencies]<br>hyper = &quot;0.12&quot;<br>futures = &quot;0.1&quot;<br>slab = &quot;0.4.2&quot;</pre><h4>The request handler for CRUD functions on the shared data</h4><p>Next, we will define a request handler called user_handler , which will parse paths from requests to perform CRUD functions on UserDb and return the corresponding responses.</p><p>The signature of user_handler is the following. It returns an implementation of the Futuretrait by value, which can be a hyper::Response&lt;Body&gt; or hyper::Error .</p><pre>fn user_handler(req: Request&lt;Body&gt;, user_db: &amp;UserDb)</pre><pre>    -&gt; impl Future&lt;Item=Response&lt;Body&gt;, Error=Error&gt;</pre><p>In order to provide RESTful APIs corresponding to CRUD functions on UserDb, we will use regular expressions to match the paths extracted from requests and handle them properly.</p><p>The path patterns we will handle for this example will be:</p><ul><li>A path for managing a single user (creating, updating and deleting).</li><li>A path for listing users.</li></ul><p>We will also use lazy_static! macro to initialize and execute regular expressions and assign the results to the created static variables.</p><p>So we add both dependencies to the Cargo.toml file, which results in:</p><pre>[dependencies]<br>hyper = &quot;0.12&quot;<br>futures = &quot;0.1&quot;<br>slab = &quot;0.4.2&quot;<br>lazy_static = &quot;1.4.0&quot;<br>regex = &quot;1.4.2&quot;</pre><p>Now we can define the regular expressions and static variables.</p><pre>lazy_static! {</pre><pre>    static ref USER_PATH: Regex = <br>        Regex::new(&quot;^/user/((?P&lt;user_id&gt;\\d+?)/?)?$&quot;).unwrap();</pre><pre>    static ref USERS_PATH: Regex = <br>        Regex::new(&quot;^/users/?$&quot;).unwrap();</pre><pre>}</pre><p>Inside the body of user_handler function, we will mainly construct a response based on identified path and the processing on UserDb , and return the response by using future::ok function.</p><pre>fn user_handler(req: Request&lt;Body&gt;, user_db: &amp;UserDb) -&gt; impl       </pre><pre>    Future&lt;Item=Response&lt;Body&gt;, Error=Error&gt; {</pre><pre>    let response = ...;</pre><pre>    ...</pre><pre>    future::ok(response)<br>}</pre><p>We will extract method and path from requests and acquire a lock on UserDb</p><pre>let response = {</pre><pre>    let method = req.method();</pre><pre>    let path = req.uri().path();</pre><pre>    let mut users = user_db.lock().unwrap();</pre><pre>    ...</pre><h4>Rust’s pattern matching for different request paths and methods</h4><p>We can proceed to math USERS_PATH and USER_PATH with just extracted path .</p><p>If requests match USERS_PATH and HTTP GET, we can iterate through users, map, and collect UserId s to a Vecof String. We finally join Vec&lt;String&gt; to a single String for responses.</p><pre>...</pre><pre>let mut users = user_db.lock().unwrap();</pre><pre>if USERS_PATH.is_match(path) {</pre><pre>    if method == &amp;Method::GET {</pre><pre>        let list = users.iter()</pre><pre>            .map(|(id, _)| id.to_string())</pre><pre>            .collect::&lt;Vec&lt;String&gt;&gt;()</pre><pre>            .join(&quot;,&quot;);</pre><pre>        Response::new(list.into())</pre><pre>    } else {<br>        response_status(StatusCode::METHOD_NOT_ALLOWED)<br>    }</pre><pre>} else if let Some(cap) = USER_PATH.captures(path) {</pre><pre>...</pre><p>If a request matches a specific USER_PATH, we can use RegEx::captures method to return a Captures with the value of captured group. Using Captures::name method, we can then get the captured value by the group name: user_id .</p><p>Once we have user_id from a request, we will use Rust’s pattern matching to handle different HTTP methods (GET, POST, PUT and DELETE).</p><pre>...<br>} else if let Some(cap) = USER_PATH.captures(path) {</pre><pre>    let user_id = cap.name(&quot;user_id&quot;).and_then(|m| {</pre><pre>                  m.as_str()</pre><pre>                   .parse::&lt;UserId&gt;()</pre><pre>                   .ok()</pre><pre>                   .map(|x| x as usize)</pre><pre>    });</pre><pre>    match (method, user_id) {</pre><pre>        (&amp;Method::GET, Some(id)) =&gt; {</pre><pre>            if let Some(data) = users.get(id) {</pre><pre>                Response::new(data.to_string().into())</pre><pre>            } else {</pre><pre>                response_status(StatusCode::NOT_FOUND)</pre><pre>            }<br>        },</pre><pre>        (&amp;Method::POST, None) =&gt; {</pre><pre>            let id = users.insert(UserData);</pre><pre>            Response::new(id.to_string().into())</pre><pre>        },</pre><pre>        (&amp;Method::POST, Some(_)) =&gt; {</pre><pre>            response_status(StatusCode::BAD_REQUEST)</pre><pre>        },</pre><pre>        (&amp;Method::PUT, Some(id)) =&gt; {</pre><pre>            if let Some(user) = users.get_mut(id) {</pre><pre>                *user = UserData;</pre><pre>                response_status(StatusCode::OK)</pre><pre>            } else {</pre><pre>                response_status(StatusCode::NOT_FOUND)</pre><pre>            }</pre><pre>        },</pre><pre>        (&amp;Method::DELETE, Some(id)) =&gt; {</pre><pre>            if users.contains(id) {</pre><pre>                users.remove(id);</pre><pre>                response_status(StatusCode::OK)</pre><pre>            } else {</pre><pre>                response_status(StatusCode::NOT_FOUND)</pre><pre>            }</pre><pre>        },</pre><pre>        _ =&gt; { </pre><pre>            response_status(StatusCode::METHOD_NOT_ALLOWED)</pre><pre>        },</pre><pre>    }</pre><pre>} else {</pre><pre>    response_status(StatusCode::NOT_FOUND)</pre><pre>}</pre><pre>...</pre><h4>Server configuration and runtime</h4><p>After defining user_handler and its implementation, we can now complete main function.</p><p>We will first create user_db using UserDb type defined earlier and then use the builder to create the server with the handler function.</p><p>The serve method of Builder struct lets us configure the server created, such as configuring support for HTTP1 and HTTP2, and attaching a function that generates a Service instance for handling HTTP requests.</p><p>We pass a closure to serve method. In the closure, will clone a reference of the shared state and call service_fn with another closure passed in. The inner closure will move the cloned reference of the shared state to user_handler function and generate a Service from it. In short, service_fn let us create a Service from a function to handle each connection.</p><pre>let user_db = Arc::new(Mutex::new(Slab::new()));</pre><pre>let server = builder.serve(move || {</pre><pre>let user_db = user_db.clone();</pre><pre>service_fn(move |req| user_handler(req, &amp;user_db))</pre><pre>});</pre><p>The Server returned from the builder’s serve method implements the Future trait with the hyper::Error type. We will further drop the error and change the error type with a new Future that hyper runtime expects. We can finally start the server with the runtime.</p><pre>let server = server.map_err(drop);</pre><pre>hyper::rt::run(server);</pre><h4>Containerization the microservices</h4><p>After the completion of coding the simple Rust microservices, we will create a Docker image with the nightly version of the Rust compiler to compile the above code and build an image with it. The Dockerfile in the repository is borrowed from <a href="https://github.com/rust-lang/docker-rust-nightly/blob/master/stretch/Dockerfile">https://github.com/rust-lang/docker-rust-nightly/blob/master/stretch/Dockerfile</a>.</p><p>First we can build the image that contains the Rust compiler.</p><pre>cd nightly<br>docker build -t rust:nightly .</pre><p>Furthermore, the Dockerfile in the root directory of the project will specify how to build and package the microservice to an image.</p><pre>FROM rust:nightly</pre><pre>RUN USER=root cargo new --bin rust-microservices</pre><pre>WORKDIR /rust-microservices</pre><pre>COPY ./Cargo.toml ./Cargo.toml</pre><pre>RUN cargo build</pre><pre>RUN rm src/*.rs</pre><pre>COPY ./src ./src</pre><pre>RUN rm ./target/debug/deps/rust_microservice*</pre><pre>RUN cargo build</pre><pre>CMD [&quot;./target/debug/rust-microservice&quot;]</pre><pre>EXPOSE 8080</pre><p>Now we can build the microservices image and run the container from it with docker-compose.</p><pre>cd ..<br>docker-compose build<br>docker-compose up -d</pre><h4>Testing</h4><p>We will use curl and run the following commands to see the results as we expect.</p><pre>curl -X POST <a href="http://localhost:8080/user/">http://localhost:8080/user/</a><br>curl -X POST <a href="http://localhost:8080/user/">http://localhost:8080/user/</a><br>curl -X POST <a href="http://localhost:8080/user/">http://localhost:8080/user/</a><br>curl -X POST <a href="http://localhost:8080/user/">http://localhost:8080/user/</a><br>curl -X DELETE <a href="http://localhost:8080/user/2">http://localhost:8080/user/2</a><br>curl http://localhost:8080/users/</pre><p>This concludes our simple implementation of a Rust microservices.</p><h4>Summary</h4><p>The simple microservices with Rust only uses some popular crates: hyper, futures, slab, regex and lazy_static , and implements simple request-response model on a simple data.</p><p>The Rust language, and more built-in and third-party crates can help us build a more full-fledged microservices with functionalities of logging, configuration, serialization and deserialization of data, data persistence, asynchronous operations, and so on.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3fbde8e32adc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Introduction to ES6]]></title>
            <link>https://genekuo.medium.com/quick-introduction-to-es6-12a4be356788?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/12a4be356788</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ecmascript-6]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Sat, 12 Oct 2019 08:42:18 GMT</pubDate>
            <atom:updated>2019-10-12T08:42:18.375Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*mbEAV3oCKqGAeo8X" /></figure><blockquote>In this article, I summarises several ES6 features and a brief introduction to the concept and usage of these features with simple examples. The main goal is to provide newcomers a quick start in making use of ES6.</blockquote><h4>let and const</h4><p>Prior to ES6, we can use var to declare a variable inside a code block and the JavaScript engine <em>hoists</em> the declaration to the top of the execution context, such as a function. This mechanism makes the variable visible outside of the block in which it is declared. It sometimes causes confusion if there are more than one variables of the same name declared inside and outside the function.</p><pre>var person = &quot;John&quot;;<br>(function () {<br>    console.log(&quot;Person inside is &quot; + person);<br>    var person = &quot;Tom&quot;;<br> })();<br>console.log(&quot;Person outside is &quot; + person);</pre><p>We can comment out var person = “Tom”; and the console will print out person inside is John person outside is John. However, if we uncomment it, the console will print out person inside is undefined person outside is John. <em>Hoisting</em> also applies to <strong>function declaration</strong> in which a function can be invoked before it is declared. However, a <em>function expression</em> is not hoisted since it is considered <em>variable initialization</em>.</p><pre>doSomething(); // TypeError: doSomething is not a function<br>var doSomething = function() {<br>  console.log(&quot;do something&quot;);<br>}</pre><p>let and const remove this confusion by using <em>block scoping</em>. let allows you declare a variable and initialize with a value, then the variable can be reassigned to another value. const can be used to initialize a variable with a value only <strong>once, however, its properties can be changed</strong>. It can not be reassigned.</p><pre>const users = [<br>  { id: 1, name: &#39;John&#39; },<br>  { id: 2, name: &#39;Mary&#39; }<br>];<br>users[0].name = &quot;Tom&quot;;<br>console.log(users);</pre><p>The following listing is an example of block scoping with let. So there is no hoisting confusion.</p><pre>let person = &quot;John&quot;;<br>(function () {<br>    console.log(&quot;Person inside function is &quot; + person);<br>    if(true) {  <br>      let person = &quot;Tom&quot;;<br>      console.log(&quot;Person inside block is &quot; + person);<br>    }<br> })();<br>console.log(&quot;Person global is &quot; + person);</pre><h4><strong>Template literals</strong></h4><p>Template literals are string surrounded by backticks (`)and allow us to write expressions inside the template literals. Strings can also span multiple lines using template literals.</p><pre>const user = &quot;John&quot;;<br>console.log(`the user is ${user}`);</pre><pre>function getUser() {<br>  return &quot;John&quot;;<br>}<br>console.log(`the user is ${getUser()}`);</pre><h4>Tagged template strings</h4><p>If a function name tags (precedes) a template string, the string is evaluated first and is passed to the function. The <em>string part</em> of the template literal will be passed as an array to the function.</p><pre>function greeting(stringParts, firstName, lastName) {<br>  console.log(stringParts);<br>  console.log(firstName);<br>  console.log(lastName);<br>}</pre><pre>const firstName = &quot;John&quot;;<br>const lastName = &quot;Tom&quot;;</pre><pre>greeting`Hello, ${firstName} ${lastName}!`</pre><h4>Optional parameters and default values</h4><p>We can specify default values as arguments to a function during the invocation of the function if no value is provided.</p><pre>function doSomething(work, place = &quot;home&quot;) {<br>  console.log(`${work} at ${place}`);<br>}</pre><pre>doSomething(&quot;reading&quot;);<br>doSomething(&quot;writing&quot;, undefined);<br>doSomething(&quot;reading&quot;, &quot;library&quot;);</pre><h4>Arrow function expressions</h4><p>Arrow function expressions represent a short notation for anonymous functions. The following listing gives examples of arrow function expressions.</p><pre>let add = (arg1, arg2) =&gt; arg1 + arg2; // the result is returned</pre><pre>(arg1, arg2) =&gt; {<br>   // do something<br>   return res; // multi-line arrow function with explicitly return<br>}</pre><pre>() =&gt; {  // without argument<br>  // do something<br>  return res;<br>}</pre><pre>arg1 =&gt; { // single argument, no parentheses needed<br>  // do something<br>}</pre><p>In addition, the following listing illustrates passing arrow function expressions to JavaScript array’s methods to operate on provided arrays.</p><pre>const arr = [1,2,3,4,5];<br>console.log(&quot;Sum is &quot; + arr.reduce((a, b) =&gt; a+b));<br>console.log(&quot;Even numbers are &quot; + arr.filter(val =&gt; val % 2 === 0));</pre><p>The this variable can have different values depending on how the function is called and on the use of <em>strict</em> mode. Array function expressions also add lexical scope for the this variable. Prior to ES6, the following constructor function sometimes confuses developers for this pointing the wrong object.</p><pre>function Greeting(message) {<br>  this.message = message;<br>  console.log(`this.message: ${this.message}`);<br>  setInterval( function () {<br>                 console.log(`greeting: ${this.message}`);<br>             }, 1000); // this.message is undefined if strict mode<br>}</pre><pre>const greeting = new Greeting(&quot;Hello world&quot;);</pre><p>We can replace the anonymous function above with the arrow function expression in the following listing to fix it.</p><pre>function Greeting(message) {<br>  this.message = message;<br>  console.log(`this.message: ${this.message}`);<br>  setInterval(() =&gt; console.log(`greeting: ${this.message}`)<br>             , 1000);<br>}</pre><pre>const greeting = new Greeting(&quot;Hello world&quot;);</pre><h4>The rest operator</h4><p>We can use the <em>rest</em> operator for a variable number of parameters in a function. The rest operator (…) <em>must be the last parameter </em>in the function signature. The function can handle the <em>rest</em> arguments as an array when it is invoked.</p><pre>function placeOrder(customer, ...products) {<br>  console.log(`Place an order for a customer: ${customer}`);<br>  products.forEach( (product) =&gt; <br>                    console.log(`Add ${product} to order`));<br>}</pre><pre>placeOrder(&quot;John&quot;, &quot;iPhone&quot;, &quot;iPad&quot;, &quot;TV&quot;);</pre><h4>The spread operator</h4><p>The <em>spread</em> operator is represented the same as the rest operator (…) but turns an array into a list of values or function arguments. In the following listing, the spread operator extracts each element of an array, and then creates a new array from those elements or processes those elements.</p><pre>let array1 = [1,2,3,4,5];<br>let array2 = [...array1];<br>console.log(array2);<br>array1.push(...array2);<br>console.log(array1);<br>const max = Math.max(...array2);<br>console.log(max);</pre><p>We often want to manage the state of an application by <strong>cloning</strong> the original state object with <strong>modification</strong> of some properties instead of directly mutating the original state object. This <strong>immutability</strong> is the best practice when managing the state of application in response to events triggered by users or systems.</p><pre>const user = { id: 1, lastName: &quot;John&quot; };<br>const clonedUser = {...user};<br>const clonedAndModifiedUser = {...user, lastName: &quot;Tom&quot;};</pre><pre>console.log(`original: ${user.lastName}`);<br>console.log(`cloned: ${clonedUser.lastName}`);<br>console.log(`cloned and modified:  ${clonedAndModifiedUser.lastName}`);</pre><p>We have to note that cloning with spread operator create a <strong>shadow</strong> copy of the object. If an object is cloned and some of its properties are also objects, <em>only the reference to the nested objects are cloned</em>. If some properties of the referenced objects changes, the clone also changes in the same way.</p><h4>Destructuring</h4><p>Destructuring extracts the structure or takes parts from an object or an array by specifying a <strong>matching pattern</strong>. Starting from ES2018, we can also use the syntax similar to rest and spread operator when destructuring objects.</p><pre>function getUser() {<br>  return {<br>      firstName: &quot;John&quot;,<br>      lastName: &quot;Tom&quot;,<br>      supervisor: {<br>        name: &quot;Mary&quot;<br>      }<br>  };<br>}</pre><pre>let { lastName, supervisor: {name}} = getUser();<br>console.log(`${lastName}`);<br>console.log(`${name}`);</pre><pre>let { firstName, ...otherInfo } = getUser();<br>console.log(`${firstName}`);<br>console.log(`${otherInfo}`);</pre><p>We can destructuring arrays by specifying variables that match array’s indexes.</p><pre>let [ name1, name2, name3 ] = [ &quot;John&quot;, &quot;Tom&quot;, &quot;Mary&quot; ];<br>let [ name4, , name5] = [ &quot;John&quot;, &quot;Tom&quot;, &quot;Mary&quot; ];<br>let [ name6, ...others] = [ &quot;John&quot;, &quot;Tom&quot;, &quot;Mary&quot; ];</pre><pre>console.log(`name1: ${name1}, name2: ${name2}, name3: ${name3}`);<br>console.log(`name4: ${name4}, name5: ${name5}`);<br>console.log(`name6: ${name6}, others: ${others}`);</pre><pre>function printUsers([ first, ...others ]) {<br>  console.log(`first: ${first}`);<br>  console.log(`others: ${others}`);<br>}<br>printUsers([ &quot;John&quot;, &quot;Tom&quot;, &quot;Mary&quot; ]);</pre><h4>Classes</h4><p>In ES5, we can use a mechanism called <strong>prototypal inheritance</strong> to create objects and inheriting from their ancestors.</p><pre>// constructor function<br>function Person(name) {<br>  this.name = name;<br>}</pre><pre>// declare additional method on its prototype<br>Person.prototype.getName = function() {<br>  return this.name;<br>}</pre><pre>// constructor function<br>function Employee(name, position) {<br>  // call Person function with employee&#39;s &quot;this&quot; and name<br>  Person.call(this, name);<br>  this.position=  position;<br>}</pre><pre>// implements inheritance by pointing at its ancestor<br>Employee.prototype = new Person();<br>// Add Employee&#39;s specific method<br>Employee.prototype.getPosition = function() {<br>  return this.position;<br>}</pre><pre>var employee = new Employee(&quot;John&quot;, &quot;developer&quot;);<br>console.log(`Employee name: ${employee.getName()}, Position: ${employee.getPosition()}`);</pre><p>ES6 introduced class and extends to give syntactic sugar to <em>simulate</em> inheritance in traditional object-oriented programming languages such as Java and C#. Even though JavaScript doesn’t allow us to declare member variables, but we can declare static variables and methods that apply to a class as a whole instead of instances.</p><p>constructor is used to denote a special function that will be called once when the object is created. Within the constructor function, we can use this which points to the current object to initialize the object’s properties.</p><p>When a subclass defines its own constructor, within the constructor, we must call super() to invoke superclass’s constructor before accessing this object or returning from the constructor. super keyword can also be used to implement method-overriding similar to some traditional object-oriented languages.</p><pre>class Person {<br>  static counter = 0;<br>  constructor(name) {<br>    this.name = name;<br>    Person.counter++<br>  }<br>  getName() {<br>    return this.name;<br>  }<br>  static getCounter() {<br>    return Person.counter;<br>  }<br>}</pre><pre>class Employee extends Person {<br>  constructor(name, position) {<br>    super(name);<br>    this.position = position;<br>  }<br>  getName() {<br>    return super.getName();<br>  }<br>  getPosition() {<br>    return this.position;<br>  }<br>}</pre><pre>let employee1 = new Employee(&quot;John&quot;, &quot;developer&quot;);<br>console.log(`Employee1 name: ${employee1.getName()}, Position: ${employee1.getPosition()}`);</pre><pre>let employee2 = new Employee(&quot;Tom&quot;, &quot;manager&quot;);<br>console.log(`Employee2 name: ${employee2.getName()}, Position: ${employee2.getPosition()}`);</pre><pre>console.log(`Total employees: ${Employee.getCounter()}`);</pre><h4>Modules</h4><p>ES6 modules are utilized to organize the application into logical and reusable units, and to expose APIs from the modules. Prior to ES6, there are multiple modules standards for implementations, such as CommonJS standard for apps running outside browsers and AMD standard for apps running inside browsers. Modules also help developers define dependencies between code and load them into the execution environment <em>on demand</em>. In ES6, a script is a module if it uses import and/or export.</p><p>The mechanism of ES6 modules can prevent us from polluting global scope with variables. It also help us to control access to our scripts and their members (classes, functions, and variables), which makes our code more manageable and maintainable.</p><p>There are named export and anonymous export. The usage is simple and is listed in the following.</p><pre>// in funcs.js<br>export function bar() { // named export<br>  console.log(&quot;bar is invoked&quot;);<br>}</pre><pre>export function foo() {<br>  console.log(&quot;foo is invoked&quot;);<br>}</pre><pre>function baz() { // private function<br>}</pre><pre>export default function {} // anonymous export</pre><pre>// in index.js<br>// destructuring and give a name to the anonymous exported function<br>import doSomthing, {foo, bar} from &#39;funcs&#39;; <br>foo();<br>doSomthing();</pre><p>All web browsers support modules in the &lt;script&gt; tag and load the script as ES6 modules.</p><pre>&lt;script type=&quot;module&quot;, src=&quot;./app.js&quot;&gt;&lt;/script&gt;</pre><h4>Promises</h4><p>JavaScript promises allow you to avoid nested <strong>callback</strong> calls and make the async code more readable. The promise object represents the future result of an asynchronous operation, which can be in one of the following states: <strong>fulfilled</strong>, <strong>rejected</strong>, and <strong>pending</strong>. We can instantiate a Promise object using its constructor with a function that has <strong>resolve</strong> and <strong>reject</strong> functions as<strong> </strong>its arguments.</p><pre>function getProducts() {<br>  return new Promise(<br>    function(resolve, reject) {<br>      console.log(&quot;Get products&quot;);<br>      // timeout 1 sec to simulate an async call<br>      setTimeout(function() {<br>        const success = true;<br>        if (success) {<br>          resolve(&quot;Success&quot;);<br>        } else {<br>          reject(&quot;Fail&quot;);<br>        }<br>      }, 1000);<br>    }<br>  );<br>}</pre><pre>getProducts()<br>  .then((prod) =&gt; console.log(prod))<br>  .catch((err) =&gt; console.error(err));<br>// the following line will print first<br>console.log(&quot;Waiting for getting products...&quot;);</pre><p>In the above example, after one second, resolve(“Success”) is called from inside the function. It results in the invocation of then() and receives “Success” as its argument.</p><p>We can also design an ordered asynchronous operations by chaining promises.</p><pre>function getUser() {<br>  return new Promise(<br>    function (resolve, reject) {<br>      console.log(&quot;Getting user&quot;);<br>      setTimeout(function() {<br>        const success = true;<br>        if (success) {<br>          resolve(&quot;user123&quot;);<br>        } else {<br>          reject(&quot;Failed&quot;);<br>        }<br>      }, 1000);<br>    }<br>  );<br>}</pre><pre>function getRoles(user) {<br>  return new Promise(<br>    function (resolve, reject) {<br>      console.log(&quot;Getting roles&quot;);<br>      setTimeout(function() {<br>        const success = true;<br>        if (success) {<br>          resolve(`Found the roles for ${user}`);<br>        } else {<br>          reject(&quot;Failed&quot;);<br>        }<br>      }, 1000);<br>    }<br>  );<br>}</pre><pre>getUser()<br>  .then((user) =&gt; {<br>           console.log(user);<br>           return user;<br>        })<br>  .then((user) =&gt; getRoles(user))<br>  .then((role) =&gt; console.log(role))<br>  .catch((err) =&gt; console.error(err));</pre><pre>console.log(&quot;Getting user and then getting roles&quot;);</pre><p>If there are multiple asynchronous operations that don’t depend on each other, we can use Promise object’s all() method that takes those promises and resolves <strong>all</strong> of them. The all() method also returns a Promise object which we can apply then() and/or catch() to the results.</p><pre>Promise.all([ getProducts(),<br>              getUser()])<br>  .then((results) =&gt; console.log(&quot;All resolved&quot;))<br>  .catch((err) =&gt; console.log(err));</pre><h4>ES8 (ES2017) : async and await</h4><p>async/await allows you to treat functions returning promises as if they are <em>synchronous</em>. async marks an asynchronous function and await marks the invocation of an async function. With await, the operation will not proceed to the next one until the invocation of an async function returns the result or throws an error.</p><pre>(async function getUserRoles() {<br>  try {<br>    const user = await getUser();<br>    console.log(`Found ${user}`);<br>    const roles = await getRoles(user);<br>    console.log(roles);<br>  } catch(err) {<br>    console.error(err);<br>  }<br>})();</pre><pre>console.log(&quot;Chained getUser and getRoles&quot;); </pre><h4>Conclusions</h4><p>There are more features in ES6 and beyond, and they are continuously improving. They are also some deep mechanisms between older JavaScript and ES6 which I purposely leave out of this article, to focus on the introduction and simple usage of ES6, instead. Hope you enjoy it. Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12a4be356788" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript: Object Modelling with Behavior Delegation]]></title>
            <link>https://genekuo.medium.com/javascript-object-modelling-with-behavior-delegation-8be99da48432?source=rss-9e756a6b0e7d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8be99da48432</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[prototype-chain]]></category>
            <category><![CDATA[delegation]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Gene Kuo]]></dc:creator>
            <pubDate>Sun, 25 Aug 2019 06:46:01 GMT</pubDate>
            <atom:updated>2019-08-25T06:46:01.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JbHFpYjbXkw49bJ7" /></figure><p><em>In JavaScript, there are no abstract blueprints for objects called “classes” as there are in traditional object-oriented languages. However, the JavaScript’s </em><em>[[prototype]] mechanism we will discuss in this article provides behavior delegation for modelling objects in an application, such as the emulation of inheritance, polymorphism, instance construction and so on. Behavior delegation has more flexible and dynamic features than those of class-based object modelling in traditional object-oriented languages.</em></p><h3>Traditional Object-oriented Approach to Object Modeling</h3><p>Many languages provides syntax which enables class-oriented software design, that is, we design parent and child classes as blueprints for objects (or instances). With traditional object-oriented language like Java, objects are instantiated by a mechanism of <em>copying</em> behavior from classes (as templates) to instances. When classes are inherited, this copying also occurs from parent classes to child classes. For polymorphism, methods at different levels of an inheritance relationship looks like referential links from child to parent classes (such as super ), but it is actually the <em>copy</em> mechanism in action from parent to child classes. So, the common scenario of object modelling in most traditional object-oriented languages goes like that: we define a parent class with shared behavior (methods) by analyzing the problem domain. Then, we can define child classes inherited from the parent class by <em>copying</em> mechanism underneath. Each child class can optionally add specialized behavior (<em>override</em>) to handle specific requirements related only to itself. The following figure illustrates the traditional object-oriented approach of modelling and design:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*98_Q_QqpP6Eb4Z2JsykrRw.png" /></figure><h3>JavaScript Prototype Mechanism</h3><p>JavaScript’s prototype mechanism is an internal link (a property named [[Prototype]] ) that exists on one object which <em>references</em> another object. When a property/method reference is requested against an object, and no such property/method exists, the internal[[Prototype]] linkage in turn requests the JavaScript engine to look for the property/method on the linked object. This is because the default [[Get]] operation follows the [[Prototype]] link of the object to reach the requested property if it cannot find the requested property on the object directly.</p><p>This linkage between objects is called the <em>prototype chain</em>. And, this prototype mechanism is what we can leverage in object modeling in JavaScript.</p><p>Since Object.create(..) creates a new object, and links that new object&#39;s internal [[Prototype]] to the object you specify, we can create a [[Prototype]] linkage between two objects using the following code.</p><pre>const obj1 = {<br>	a: 5<br>};<br>// create an object linked to obj1<br>const obj2 = Object.create( obj1 );<br>myObject.a; // 5</pre><h3>Emulating Classes using Functions</h3><p>All functions in JavaScript by default get a property on them called prototype , which points to an arbitrary object, for the example below, User.prototype object. And, when a function is called with new , an object is created and it gets an internal [[prototype]] link to the object that the function’s prototype is pointing at. By default, User.prototype gets a public, non-enumerable property called constructor , which is a reference to the function itself, User in this case. However, the object user1 or user2 created by the call new User() does not mean it was constructed by User constructor (just a side-effect of the new call), even user1.constructor === User is true. user1 does not have a constructor property pointing at User, instead user1.constructor points at User via [[prototype]]mechanism as described previously.</p><pre>function User(name) {<br>	this.name = name;<br>}<br>User.prototype.myName = function() {<br>    return this.name;<br>}<br>const user1 = new User(&quot;a&quot;);<br>const user2 = new User(&quot;b&quot;); </pre><pre>Object.getPrototypeOf(user1) === User.prototype; //true<br>User.prototype.constructor === User; // true<br>user1.constructor === User; // true</pre><pre>user1.myName(); // a<br>user2.myName(); // b</pre><p>In traditional object-oriented languages, the process of instantiating (or inheriting from) a class exercises the mechanism of <em>copying</em> the defined behavior from that class into a physical object to create each new instance. However, as we can see in JavaScript, we don’t create multiple instances of a class. Instead, we create multiple objects (such as const user1 = )that [[Prototype]] link to a common object.</p><p>Trying to emulate class-oriented design with JavaScript as those in traditional object-oriented languages, such as classes, constructors, new, copy operations, inheritance, and polymorphism, will often lead to much confusion about how JavaScript actually works. <em>Capitalized</em>-named functions called with new to create a JavaScript object does not mean the function is a constructor and its name is the name of a class. Functions are just plain normal functions, not constructors, and there are no copy operations from classes to instances when using new on functions. There are only objects [[prototype]] linked to other objects which the property and function access can be delegated to.</p><p>Sonew User() is the implicit way to create a new object linked to another object, and there are another way, Object.create(..) , is the explicit way to create a new object linked to another object.</p><h3>Prototypal Inheritance</h3><p>There is no real “<em>classical inheritance</em>” in JavaScript since inheritance implies a copy operation, and JavaScript doesn’t use the copy operation and instead uses prototype mechanism to create links between two objects, which allows one object to delegate property and function access to another object.</p><p>Based on prototype mechanism, we can say that user1 can have [[prototype]] link to User.prototype for property and function delegation. And, we can also form the concept of a parent-child “class” inheritance, such as linkage fromEmployee.prototype “object” to User.prototype “object”, to resemble the class inheritance in traditional object-oriented languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*sLuTgq62_kXxR-EO5zvujA.png" /></figure><p>The following code listing illustrates the prototype mechanism in action, and the resemblance of class-inheritance in traditional object-oriented languages.</p><pre>function User(name) {<br>    this.name = name;<br>}<br><br>User.prototype.getName = function() {<br>    return this.name;<br>};<br><br>function Employee(name, position) {<br>    User.call(this, name);<br>    this.position = position;<br>}</pre><pre>// Make a new Employee.prototype linked to User.prototype<br>// Employee.prototype.constructor is gone<br>Employee.prototype = Object.create(User.prototype);</pre><pre>Employee.prototype.myPosition = function() {<br>    return this.position;<br>};<br><br>const john= new Employee( &quot;John&quot;, &quot;Developer&quot; );<br><br>john.myName(); // &quot;John&quot;<br>john.myPosition(); // &quot;Developer&quot;</pre><h3>ES6 Classes</h3><p>With the introduction of ES6&#39;s class and super, which provides a syntactic sugar to eliminate the ugliness of various prototype related calls seen previously, and to emulate traditional object-oriented class related concepts and syntax; since those are not real classes, and they still base on the [[prototype]] mechanism we discuss earlier. We, as developers, have a choice to how to design an object model based on ES6 syntactic sugar, or to design it based on behavior delegation or mixins more flexibly.</p><pre>class User {<br>    constructor(name) {<br>        this.name = name;<br>    }</pre><pre>    getName() {<br>        return this.name;<br>    }<br>}</pre><pre>class Employee extends User {<br>    constructor(name, position) {<br>        super(name);<br>        this.position = position;<br>    }</pre><pre>    getName() {<br>        return super.getName();<br>    }</pre><pre>    getPosition() {<br>        return this.position;<br>    }<br>}</pre><pre>const john = new Employee(“John”, “Developer”);<br>john.getName(); // &quot;John&quot;<br>john.getPosition(); // &quot;Developer&quot;</pre><h3>Behavior Delegation</h3><p>Behavior Delegation leverages JavaScript’s prototype mechanism (linking objects to other objects<strong>) </strong>which lets some object provide a delegation to common utility objects for property or method references if not found on the object itself. This is very different from the traditional object-oriented design pattern. There are no parent and child classes, inheritance, polymorphism, etc. We can view objects in JavaScript as <em>horizontally</em> peered objects and they can be linked side-by-side to from the delegation linkage as necessary. Unlike the traditional object-oriented languages, there are no complex inheritance levels to consider and no copying mechanism happening.</p><pre>const User = {<br>    init(name) {<br>        this.name = name;<br>    },<br>    getName() {<br>        return this.name;<br>    }<br>};</pre><pre>const Employee = Object.create(User);</pre><pre>Employee.build = function(name, position) {<br>    this.init(name);<br>    this.position = position;<br>};<br>Employee.outputDetails = function() {<br>    console.log(this.getName() + &quot; is a &quot; + this.position);<br>};</pre><pre>const john = Object.create(Employee);<br>john.build(&quot;John&quot;, &quot;Developer&quot;); </pre><pre>const mary = Object.create(Employee);<br>mary.build(&quot;Mary&quot;, &quot;Manager&quot;);</pre><pre>john.outputDetails(); // John is a Developer<br>mary.outputDetails(); // Mary is a Manager</pre><p>In the following listings, we will use more concrete example for illustrating behavior delegation in JavaScript, focusing on simple web UI design.</p><p>We first must load jQuery into our Browser’s (Chrome, for example) developer tool.</p><pre>let script = document.createElement(&quot;script&quot;);<br>script.setAttribute(&#39;src&#39;, &#39;https://code.jquery.com/jquery-    latest.min.js&#39;);<br>script.addEventListener(&#39;load&#39;, function() {<br>        let script = document.createElement(&#39;script&#39;);<br>        document.body.appendChild(script);<br>    }, false);<br>document.body.appendChild(script);</pre><p>Then, we declare a variable Widget pointing to an object with init() and insert() utilities for other objects to link and delegate behavior to.</p><pre>const Widget = {<br>    init(width,height){<br>        this.width = width || 50;<br>        this.height = height || 50;<br>        this.$elem = null;<br>    },<br>    insert($where){<br>        if (this.$elem) {<br>            this.$elem.css({<br>                width: this.width + &quot;px&quot;,<br>                height: this.height + &quot;px&quot;<br>            }).appendTo($where);<br>        }<br>    }<br>};</pre><p>The Button object we define here can be independent from the previousWidget object. They are now just peer-to-peer objects.</p><pre>const Button = {<br>    setup(width,height,label){<br>        // delegated call<br>        this.init(width, height);<br>        this.label = label || &quot;Default&quot;;<br>        this.$elem = $(&quot;&lt;button&gt;&quot;).text(this.label);<br>    },<br>    build($where) {<br>        // delegated call<br>        this.insert($where);<br>        this.$elem.click(this.onClick.bind(this));<br>    },<br>    onClick(evt) {<br>        console.log(&quot;Button &#39;&quot; + this.label + &quot;&#39; clicked!&quot;);<br>    }<br>};</pre><p>Now, we can set the prototype (i.e., the internal [[Prototype]] property) of Button to a new prototype, which is Widget.</p><pre>Object.setPrototypeOf(Button, Widget);</pre><p>Finally, we can test it on a browser to see behavior delegation in action.</p><pre>$(document).ready(function(){<br>    const $body = $(document.body);<br>    const btn1 = Object.create(Button);<br>    btn1.setup(120, 30, &quot;A&quot;);</pre><pre>    const btn2 = Object.create(Button);<br>    btn2.setup(150, 50, &quot;B&quot;);</pre><pre>    btn1.build($body);<br>    btn2.build($body);<br>} );</pre><h3>Conclusions</h3><p>In JavaScript, the [[Prototype]] mechanism links objects to other objects. There are no abstract mechanisms like &quot;<em>classes</em>&quot;, no matter how much we try to convince ourselves otherwise.</p><p>As we can see, behavior delegation is the more natural way to model objects in JavaScript. It leverages the prototype lookup process to enable peered objects to delegate behavior with each other without strictly declaring class hierarchy or tightly-coupled composition, like in traditional object-oriented languages.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8be99da48432" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>