<?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 Tobin on Medium]]></title>
        <description><![CDATA[Stories by Tobin on Medium]]></description>
        <link>https://medium.com/@tobinc?source=rss-246370aaad7e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*9NAwzlHyxA8XPHV8xR73dA.jpeg</url>
            <title>Stories by Tobin on Medium</title>
            <link>https://medium.com/@tobinc?source=rss-246370aaad7e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 23:26:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tobinc/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[Speeding up NextJS on AWS Amplify: CloudFront - Cache it Real Good]]></title>
            <link>https://awstip.com/nextjs-aws-amplify-cloudfront-cache-it-real-good-1211466cecfd?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/1211466cecfd</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[cloudfront]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[amplify]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Sat, 17 Jun 2023 21:12:58 GMT</pubDate>
            <atom:updated>2026-03-18T18:48:44.322Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a follow on from <a href="https://tobinc.medium.com/speeding-up-aws-amplify-nextjs-first-render-cold-start-and-images-an-unexpected-result-36a416d69615">Part 1: Speeding up first render</a>.</p><p><a href="https://aws.amazon.com/amplify/">AWS Amplify</a> renders <a href="https://nextjs.org/">NextJS </a>apps using an Edge Lambda running in CloudFront. My current test project <a href="https://proofenance.com/">Proofenance</a> renders in NextJS and handles the API through <a href="https://aws.amazon.com/pm/appsync/">AppSync</a>. This CF has a cache policy which provides a minimum of 2 seconds on everything, and caps the maximum to 10 minutes. Importantly, the Edge Lambda container will die very roughly every 10-120 minutes and all of its internal NextJS runtime cache (i.e. resized images) will disappear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kCqrgRZzN2TT1bKGqqBj9g.png" /><figcaption>Managed cache control policy</figcaption></figure><p>For images which were statically imported, and therefore cached during build phase and requested from an &lt;img/&gt; tag, serving from the Lambda is still hindered by the Lambda’s execution time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*btzwZVvbb4BvS9-MUUSFfg.png" /><figcaption>First request for an image which was statically exported.</figcaption></figure><p>This effect is even further amplified where the browser starts making parallel requests which require more Lambda containers to cold start.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tZK1NxODCQ48E3S-pa4NYg.png" /></figure><p>On the face of it, this is OK. A 2 second minimum cache reduces parallel requests from multiple viewers on uncached pages (NextJS does not automatically cache pages). A 10 minute maximum is not ideal but is not the end of the world.</p><h3>However</h3><p>The CloudFront cache policy includes the cookie string on the cache key (along with the usual query params etc). This is problematic because if your webapp puts anything identifierable onto the cookie (e.g. Google Analytics Id), this cookie can be sent with every request to the domain and force every user to have their own cache key. This pretty much nullifies the cache entirely; for a single user the requests will be quicker the next time (as we see above) but many parallel users will spawn many parallel Lambdas.</p><h4>Is this a problem?</h4><p>Absolutely. With new accounts AWS appears to allow merely 10 concurrent Lambda executions which is very quickly consumed by Amplify — 3 users accessing our Amplify / NextJS landing page in parallel was sufficient to get an ugly 503 unavailable AWS error as the landing page! Getting this extended to 1000 concurrent Lambdas would theoretically allow 300 parallel users.</p><h3>Solution</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*kO5u_KZZREhCCEpKncf1TA.png" /><figcaption>The solution is always to add more</figcaption></figure><p>This is helped by adding a fresh, completely controllable CloudFront Distribution in front of the Amplify one. The fronting CF has a source of the Amplify own-brand URLs for your project:</p><pre>master.d3724myumjmiwv.amplifyapp.com</pre><p>The goals for this are:</p><ol><li>Cache key for /_next/static/* public data, to ignore cookies and include query params, and listen to the cache-control header [<strong>CacheBehaviour 1</strong>]</li><li>Include cookies (and Authorisation header) in the cache key for all other routes + /_next/data/* + pages (as it currently does) [<strong>Default</strong> <strong>CacheBehaviour</strong>]</li><li>Remove all caching on the /api/* routes [<strong>CacheBehaviour 2</strong>]</li><li>Evict the page cache on deployment. Images and static data are cache busted by NextJS automatically so do not need eviction ($$).</li><li>If you are not using authenticated SSR, then all the routes could have cookies excluded.</li></ol><h3>Create the CloudFront</h3><pre>CachePolicyNextStatic:<br>    Type: AWS::CloudFront::CachePolicy<br>    Properties:<br>      CachePolicyConfig:<br>        DefaultTTL: 86400<br>        MaxTTL: 31536000<br>        MinTTL: 2<br>        Name: &quot;next-static&quot;<br>        ParametersInCacheKeyAndForwardedToOrigin:<br>          CookiesConfig:<br>            CookieBehavior: none #Ignore all cookies<br>          EnableAcceptEncodingBrotli: true<br>          EnableAcceptEncodingGzip: true<br>          HeadersConfig:<br>            HeaderBehavior: none  # Ignore all headers<br>          QueryStringsConfig:<br>            QueryStringBehavior: all # Send all query params (e.g. url for images)<br>  CloudFrontMain:<br>    Type: AWS::CloudFront::Distribution<br>    Properties:<br>      DistributionConfig:<br>        Aliases:<br>          - proofinance.co.uk<br>        CacheBehaviors:<br>          - AllowedMethods: [HEAD, GET, OPTIONS]<br>            CachePolicyId: !Ref CachePolicyNextStatic # static policy for the next static files<br>            Compress: true<br>            OriginRequestPolicyId: 216adef6-5c7f-47e4-b989-5492eafa07d3 # Basic policy to send all fields (cookies, headers, query strings)<br>            PathPattern: /_next/static/*<br>            TargetOriginId: master # All routes pointing to Amplify<br>            ViewerProtocolPolicy: redirect-to-https<br>          - AllowedMethods: [HEAD, DELETE, POST, GET, OPTIONS, PUT, PATCH]<br>            CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad # Don&#39;t cache anything for the /api routes<br>            Compress: true<br>            OriginRequestPolicyId: 216adef6-5c7f-47e4-b989-5492eafa07d3<br>            PathPattern: /api/*<br>            TargetOriginId: master<br>            ViewerProtocolPolicy: redirect-to-https<br>        DefaultCacheBehavior:<br>          AllowedMethods: [HEAD, DELETE, POST, GET, OPTIONS, PUT, PATCH]<br>          CachePolicyId: 2e54312d-136d-493c-8eb9-b001f22f67d2 # The Managed Policy for Amplify<br>          Compress: true<br>          OriginRequestPolicyId: 216adef6-5c7f-47e4-b989-5492eafa07d3<br>          TargetOriginId: master<br>          ViewerProtocolPolicy: redirect-to-https<br>        Enabled: true<br>        HttpVersion: http2and3<br>        IPV6Enabled: true<br>        Origins:<br>          - CustomOriginConfig:<br>              OriginProtocolPolicy: https-only<br>            DomainName: master.d3724myumjmiwv.amplifyapp.com # This distribution is just for master branch<br>            Id: master<br>        PriceClass: PriceClass_100<br>        ViewerCertificate:<br>          AcmCertificateArn: ${self:custom.certificateArn} # ACM certificate<br>          SslSupportMethod: sni-only<br>          MinimumProtocolVersion: TLSv1.2_2019<br>  IPV4Route53:<br>    Type: AWS::Route53::RecordSet<br>    Properties:<br>      HostedZoneId: Z1RWWTK7YXVZ5X<br>      Name: proofenance.co.uk<br>      Type: A<br>      AliasTarget:<br>        DNSName: !GetAtt CloudFrontMain.DomainName<br>        HostedZoneId: Z2FDTNDATAQYW2<br>  IPV6Route53:<br>    Type: AWS::Route53::RecordSet<br>    Properties:<br>      HostedZoneId: Z1RWWTK7YXVZ5X<br>      Name: proofenance.co.uk<br>      Type: AAAA<br>      AliasTarget:<br>        DNSName: !GetAtt CloudFrontMain.DomainName<br>        HostedZoneId: Z2FDTNDATAQYW2</pre><p>Something neat I learnt making this; the CloudFront CachePolicy is able to decode incoming cookies, and selectively send or exclude specific cookie values to the origin.</p><h4>How to Front CloudFront with CloudFront</h4><p>AWS recommends not to do this because of performance issues, which is certainly a good point. It can also make things like caching and routing behaviours a headache to work out. <a href="https://github.com/aws-amplify/amplify-hosting/issues/2812">Highlighted in this issue</a> is the point that the Amplify CloudFront is locked down and we don’t have access to the really awesome features in CF. It appears to me that the Origin CF detects a CF origin request by seeing the incoming headers (or maybe vice versa?). We can enable fronting by blocking headers in the fronting CF Cache Policy:</p><pre>HeadersConfig:<br>  HeaderBehavior: none</pre><p>Of course this means no headers, so perhaps whitelisting or specifying only some routes to allow all (which have a different origin).</p><h4>Evicting the cache on deploy</h4><p>There currently (2023) isn’t a simple method for executing arbitrary code after an Amplify build and deployment process has completed. Instead, Amplify provides a basic Notifications entry to email status updates to an email address. Under the hood, Amplify creates a subscription to an SNS topic. This topic can be leveraged to notify other services like Lambda via other subscriptions.</p><pre>invalidator:<br>  handler: functions/invalidator/index.handler<br>  environment:<br>    CloudFrontMainDomain: !GetAtt CloudFrontMain.DomainName<br>  iamRoleStatements:<br>    - Effect: Allow<br>      Action:<br>        - cloudfront:createInvalidation<br>      Resource: !Sub arn:aws:cloudfront::*:distribution/${CloudFrontMain}<br>  events:<br>    sns: ${self:custom.amplifySnsTopic}</pre><p>A Lambda log of the event will receive this message after the deployment:</p><blockquote>“Build notification from the AWS Amplify Console for app: <a href="https://dev.d3724myumjmiwv.amplifyapp.com/">https://dev.d3724myumjmiwv.amplifyapp.com/</a>. Your build status is SUCCEED. Go to <a href="https://console.aws.amazon.com/amplify/home?region=eu-west-2#d3724myumjmiwv/dev/125">https://console.aws.amazon.com/amplify/home?region=eu-west-2#d3724myumjmiwv/dev/125</a> to view details on your build.</blockquote><p>Matching on the SUCCEED means that the CloudFront is ready to be invalidated, with the urls to invalidate. All the NextJS reference files (and page JSONs) have cache busting through versioning in the name, so only the entry pages need to be invalidated.</p><pre>var params = {<br>  DistributionId: process.env.CloudFrontMainDomain,<br>  InvalidationBatch: {<br>    CallerReference: event.Records[0].Sns.MessageId,<br>    Paths: {<br>      Quantity: 2,<br>      Items: [<br>        &#39;/&#39;,<br>        &#39;/security/kyc-aml-id-verification&#39;<br>      ]<br>    }<br>  }<br>};<br>cloudfront.createInvalidation(params, function(err, data) {<br>  if (err) console.log(err, err.stack); // an error occurred<br>  else     console.log(data);           // successful response<br>});</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1211466cecfd" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/nextjs-aws-amplify-cloudfront-cache-it-real-good-1211466cecfd">Speeding up NextJS on AWS Amplify: CloudFront - Cache it Real Good</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Speeding up AWS Amplify NextJS First Render + Cold Start: An Unexpected Result!]]></title>
            <link>https://awstip.com/speeding-up-aws-amplify-nextjs-first-render-cold-start-and-images-an-unexpected-result-36a416d69615?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/36a416d69615</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[route-53]]></category>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[aws-amplify]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Fri, 26 May 2023 10:07:24 GMT</pubDate>
            <atom:updated>2026-03-18T18:50:00.571Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://aws.amazon.com/amplify/">AWS Amplify</a> has fantastic automatic deployment for NextJS apps, including SSR. Amplify builds the NextJS app and deploys it as an Edge Lambda into its own CloudFront. The CloudFront has some limited (but very easy to use) configurability through the Amplify Console. I was having sluggish performance on my test project <a href="https://proofenance.com/">Proofenance</a> and used these techniques to massively decrease the SSR page code, bundle sizes and loading times; and increase the Lighthouse score.</p><p>The app is constructed with entirely frontend authentication. This means all SSR requests are not authenticated and will return generic content; leaving the frontend to fetch data with an authenticated API request after page load. I have found this works better for <a href="https://proofenance.com/">Proofenance</a> as it much reduces the Time To First Byte, especially on cold starts.</p><h3>Contents</h3><ol><li>Before and After</li><li>Decreasing bundle size</li><li>Setting up full cache control</li><li>Clearing CloudFront cache on deployment</li></ol><h3>The Before</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*bk4neZ3WRVu1pzmbbYWVwQ.png" /><figcaption>Pretty awful NextJS results.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e6SrOeU-jAwedOmAiHw6RQ.png" /><figcaption>Gross unused js</figcaption></figure><p>Using SSR gets around a bit of the JS loading, as the user can still view the page before it&#39;s finished loading.</p><h4>Long Cold Start times at first-page entry</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PvfogEeLRf2-62Aqtnp1FA.png" /><figcaption>Extra long Cold Start</figcaption></figure><h4>Careless package inclusions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMA9r8F9rezEj5o1o2s0pQ.png" /><figcaption>Browser bundle analysis — 3.69MB</figcaption></figure><h3>The after</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*p1E8I9mUVp6nVukKjNf1DQ.png" /><figcaption>Not perfect but a lot better</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fBuPfA6ftxqkZI93hQJ7Sw.png" /><figcaption>Better but still chunky — 2.17MB</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fvtUP3NduHLezQb_QEA--g.png" /><figcaption>Looking better!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/969/1*vTHeUi5dNFcXNw6txKlHKQ.png" /><figcaption>S-S-S-Speeeeeed Boost!</figcaption></figure><h3>Decreasing bundle size</h3><p>The core techniques are to try and remove or treeshake libraries, and dynamically import libraries which can be deferred. NextJS will take care of modularising them after.</p><p>First to tackle is <a href="https://www.npmjs.com/package/react-pay-icons">react-pay-icons</a> which is quite large. For this I went back to basics and did the icons individually in Figma, exported as .svg and statically imported into Next Image from my public folder.</p><h4>Removing @aws-amplify from the static imports</h4><p>The single module file shown above named _app-…js is required to be ready for every page to load (determined by _app.ts ). The bundle analysis clearly shows the biggest component is the Amplify suite and particularly GraphQL.</p><p>As a landing page, it should have all static information rendered as fast as possible. We then want to know if the user is authenticated or not for the Navbar login status icon.</p><p>The surprising benefit here — the app file must be loaded by the Edge Lambda during every page’s SSR. This adds an overhead of time consumption for every. single. request. By removing the static amplify import, we benefit everywhere.</p><p>Let&#39;s get to the code. We need 3 states for the login status: null false true. The SSR must not try to load Amplify Auth and will return null which will persist in the browser until Auth.currentUserPoolUser returns an answer locally.</p><p>First, change your an amplifyConfig method to use dynamic imports:</p><pre>// BEFORE (shortened)<br>import { Amplify } from &quot;@aws-amplify/core&quot;;<br>const amplifyConfig = () =&gt; {<br>  const identityPoolId = nextPublicEnvironment.identityPoolId;<br>  const Auth = {<br>    identityPoolId,<br>    ...<br>  };<br>  Amplify.configure({<br>    Auth,<br>  });<br>};<br>export default amplifyConfig;</pre><pre>// AFTER (shortened)<br>const amplifyConfig = async () =&gt; {<br>  const { Amplify } = await import(&quot;@aws-amplify/core&quot;);<br>  const identityPoolId = nextPublicEnvironment.identityPoolId;<br>  const Auth = {<br>    identityPoolId,<br>    ...<br>  };<br>  Amplify.configure({<br>    Auth,<br>  });<br>};<br>export default amplifyConfig;</pre><p>This defers loading of the actual javascript files/modules until the function is called, sometime after the page has rendered for the user in the browser with a useEffect.</p><pre>// _app.tsx or a global context<br>useEffect(() =&gt; {<br>    import(&quot;@aws-amplify/core&quot;).then(async (Amplify) =&gt; {<br>      const amplifyConfig = (await import(&quot;components/utils/amplifyConfig&quot;))<br>        .default;<br>      await amplifyConfig();<br>      setAmplifyConfigured(true);<br>    });<br>  }, []);</pre><p>Any Amplify API, Auth, etc functions will throw an error if they are invoked before Amplify has been configured. Therefore every Amplify import now has to be dynamically imported after Amplify has been configured.</p><pre>// Profile Context Provider<br>export const ProfileContextProvider = ({<br>  children,<br>}: ComponentProps&lt;FC&gt;): JSX.Element =&gt; {<br>  const { amplifyConfigured } = useGlobalContext();<br>  const [state, setProfileState] = useState&lt;ProfileState&gt;({<br>    ...<br>  });<br><br>  const establishUser = useCallback(async () =&gt; {<br>    const { Auth } = await import(&quot;@aws-amplify/auth&quot;);<br>    const isLoggedIn = await Auth.currentUserPoolUser({<br>      bypassCache: true,<br>    })<br>      .then((user) =&gt; !!user)<br>      .catch(() =&gt; false);<br>    let profile: ProfileState;<br>    ... // GraphQL fetch<br>    setProfileState(profile);<br>  }, [amplifyConfigured]);<br><br>  useEffect(() =&gt; {<br>    if (amplifyConfigured) {<br>      establishUser();<br>    }<br>  }, [amplifyConfigured, establishUser]);<br><br>  return (<br>    &lt;ProfileContext.Provider<br>      value={{<br>        state,<br>      }}<br>    &gt;<br>      {children}<br>    &lt;/ProfileContext.Provider&gt;<br>  );<br>};</pre><p>Let me know any questions in the comments. Using this technique, the server does not load any Amplify libraries at all, and the browser has fully deferred loading Amplify javascript until after render.</p><h4>Removing crypto/browserify</h4><p>This exists because somewhere in my code I have imported a package which uses the native Node crypto package. This is fine within SSR but as crypto is not available in the browser, NextJS has automatically shimmed it for me. Given the size of this package, realistically I should refactor my code to see if it can be excluded.</p><p>Drilling down, I had used <a href="https://www.npmjs.com/package/jsonwebtoken">jsonwebtoken</a> in a component used in the browser, as well as SSR. The business logic required only decoding and viewing the expiry date so I changed it for <a href="https://www.npmjs.com/package/jwt-decode">jwt-decode</a> .</p><h3>Reducing first render + cold start time</h3><p>The very first request will pass through CloudFront and trigger the Edge Lambda to render. The CloudFront team have created a <a href="https://us-east-1.console.aws.amazon.com/cloudfront/v3/home?region=eu-west-2#/policies/cache/2e54312d-136d-493c-8eb9-b001f22f67d2">Managed Policy for Amplify</a> which effectively offers a 2-second minimum cache for everything. My <a href="https://medium.com/@tobinc/nextjs-aws-amplify-cloudfront-cache-it-real-good-1211466cecfd">NextJS CloudFront Caching</a> article goes into detail on how to optimise this for your application.</p><p>Without optimised caching, the most important thing is to keep the Lambda warm. The easiest way to do this is to set up a <a href="https://us-east-1.console.aws.amazon.com/route53/healthchecks/home">Route 53 Health Check</a>. Every health check ping will warm an Edge Lambda in the health check region, and charge a CloudFront response. To reduce costs, only select the health checker regions to match your desired regions. I used the Amplify domain because hitting the real domain will charge DNS lookups.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DzQXI02169p52rsnhqqDQ.png" /><figcaption>Setup the health check</figcaption></figure><p>Viewing the Cost Explorer quickly tells us where the Edge Lambdas have warmed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*473Mbrv2K7Jb30_U8_dvLg.png" /><figcaption>Result and cost (daily)</figcaption></figure><p>The total cost is approximately $1.10 per month ($1 for R53 + $0.10 for CF / Lambda).</p><p>If you liked this article, send a clap and check out <a href="https://medium.com/@tobinc/nextjs-aws-amplify-cloudfront-cache-it-real-good-1211466cecfd">Part 2: Caching</a>. Validate this article: see how the <a href="https://proofenance.co.uk/">Proofenance</a> site performs for you and comment your thoughts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=36a416d69615" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/speeding-up-aws-amplify-nextjs-first-render-cold-start-and-images-an-unexpected-result-36a416d69615">Speeding up AWS Amplify NextJS First Render + Cold Start: An Unexpected Result!</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deploying Serverless Framework on AWS Amplify]]></title>
            <link>https://awstip.com/deploying-serverless-framework-on-aws-amplify-74390e1a400c?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/74390e1a400c</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[serverless-framework]]></category>
            <category><![CDATA[serverless]]></category>
            <category><![CDATA[nextjs]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Tue, 09 May 2023 20:30:46 GMT</pubDate>
            <atom:updated>2023-08-03T07:07:59.023Z</atom:updated>
            <content:encoded><![CDATA[<p>A guide to deploying Serverless Framework YAML in AWS Amplify. This allows us to use the CI functionality in Amplify, deploy a hosted NextJS app, and deploy a full serverless.yaml into the correct stage. This is how I host <a href="https://proofenance.co.uk/">Proofenance</a> (the current side project).</p><p>Register the Serverless App with Serverless, and log in on your Command. Optionally deploy into each stage to create them in the Serverless Console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/1*oHEQmflrfTMShB2IucqGeQ.png" /><figcaption>Config in Serverless.yml</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*reCr4o-TXQ_8gtP0OyKDDA.png" /><figcaption>App and Stages created</figcaption></figure><p>In the Org Access Keys screen, you can see the Access Key created by the sls login from local. Use add to create a new Access Key for Amplify.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_cjziXeHbh-K7n_xwqX9Q.png" /><figcaption>Serverless console</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*_ljrzVTofTuHSi1fZBvkoA.png" /></figure><p>Within Amplify, find the Environment Variables page. Set up the variables like this, with STAGE to match your stage names. In this case, I have the default dev stage from Serverless, and an explicit production stage name.</p><p>Add a var SERVERLESS_ACCESS_KEY for all branches with the new Access Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3D6k5doQdlRfauDYvSKsGg.png" /><figcaption>Setting up the environment</figcaption></figure><p>These vars are only for the Build phase in AWS Amplify. The Deploy phase is taken care for us by Amplify. Within the Build phase are 2 subphases Frontend and Backend , within those are 2 more sub-subphases preBuild and build .</p><p>When setting up AWS Amplify, it will automatically create an amplify.yml , modify or replace it with the below</p><pre># amplify.yml<br><br>version: 1<br>backend:<br>  phases:<br>    preBuild:<br>      commands:<br>        - yarn install<br>    build:<br>      commands:<br>        - yarn sls package --stage ${STAGE} --region eu-west-2 --verbose<br>        - yarn sls deploy --package ./.serverless --stage ${STAGE}<br>frontend:<br>  phases:<br>    preBuild:<br>      commands:<br>        - yarn install<br>    build:<br>      commands:<br>        - yarn run build<br>  artifacts:<br>    baseDirectory: .next<br>    files:<br>      - &quot;**/*&quot;<br>  cache:<br>    paths:<br>      - node_modules/**/*</pre><p>The previously defined STAGE variable will populate into these commands. Personally I prefer the maximum verbose because when it goes wrong things are a bit easier.</p><p>As the build container does not have serverless installed at command level so within package.json is</p><pre># package.json<br><br>&quot;scripts&quot;: {<br>    &quot;sls&quot;: &quot;sls&quot;, </pre><p>Pushing onto dev branch will now trigger a serverless build, then serverless deploy.</p><h3>Exporting outputs from the CloudFormation stack to the NextJS build</h3><p>Using the Amplify browser SDK requires a configuration JSON which the Amplify CLI (or Amplify Studio) creates. This must be recreated by importing various values generated by the CloudFormation deployment like the Cognito UserPoolId. Add this Serverless plugin and file:</p><pre># serverless.yml<br><br>plugins:<br>  - serverless-stack-output<br><br>custom:<br>  output:<br>    handler: serverless/outputs.handler</pre><pre>// serverless/outputs.js<br><br><br>const { SSM } = require(&quot;aws-sdk&quot;);<br>const ssm = new SSM({<br>  region: &quot;eu-west-2&quot;,<br>});<br><br>const handler = async (outputs, { serviceOutputs }, { stage }) =&gt; {<br>  console.log(&quot;outputs&quot;, outputs);<br>  console.log(&quot;serviceOutputs&quot;, serviceOutputs);<br>  console.log(&quot;stage&quot;, stage);<br><br>  for (let name in outputs) {<br>    const Value = outputs[name];<br>    const Name = `/proofinance/${stage}/stack/${name}`;<br>    const { Parameter } = await ssm<br>      .getParameter({<br>        Name,<br>      })<br>      .promise()<br>      .catch((e) =&gt; {<br>        return { Parameter: { Value: undefined } };<br>      });<br>    if (Parameter.Value === Value) {<br>      console.log(`No change ${Name} =&gt; ${Value}`);<br>    } else {<br>      await ssm<br>        .putParameter({<br>          Name,<br>          Value,<br>          Overwrite: true,<br>          Type: &quot;String&quot;,<br>        })<br>        .promise();<br>      console.log(`Set ${Name} =&gt; ${Value}`);<br>    }<br>  }<br>};<br><br>module.exports = {<br>  handler,<br>};</pre><p>This will place all the serverless outputs into the Systems Manager Parameter Store. For non-secrets, this is a very cost-effective way to store config values (they should all be NEXT_PUBLIC_ compatible).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j8uMniDmCWWj70TvCaMZCg.png" /><figcaption>SSM Params as they come though</figcaption></figure><h4>Importing into next.config.js</h4><p>The values are read directly from the Param store at build time, and inlined by NextJS.</p><pre>// next.config.js<br><br>module.exports = async (phase, { defaultConfig }) =&gt; {<br>  /** @type {import(&#39;next&#39;).NextConfig} */<br>  const nextConfig = {<br>    reactStrictMode: true,<br>  };<br><br>  const [<br>    NEXT_PUBLIC_USERPOOL_ID,<br>  ] = await Promise.all([<br>    getParameterValue(`UserPoolId`),<br>  ]);<br><br>  nextConfig.env = {<br>    NEXT_PUBLIC_DOMAIN: &quot;proofenance.co.uk&quot;,<br>    NEXT_PUBLIC_USERPOOL_ID,<br>  };<br><br>  return nextConfig<br>};</pre><p>The last piece of the puzzle is allowing the build container to read SSM, and modify the logging Service Role created by the AWS Amplify console to work with SSM:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ChbB5u3JKgmrP-xVRRJ8Ew.png" /><figcaption>Modified logging service role</figcaption></figure><h4>Further Reading</h4><ul><li><a href="https://gethelios.dev/blog/opentelemetry-tracing/">OpenTelemetry Tracing: Everything you need to know</a></li><li><a href="https://gethelios.dev/blog/opentelemetry-python/">OpenTelemetry Python - Walkthrough and monitoring Examples</a></li><li><a href="https://gethelios.dev/blog/api-observability-leveraging-otel-to-improve-developer-experience/">API observability: Leveraging OTel to improve developer experience - gethelios.dev</a></li><li><a href="https://gethelios.dev/blog/evaluating-distributed-tracing-tools-a-guide/">Evaluating distributed tracing tools: A guide - gethelios.dev</a></li><li><a href="https://gethelios.dev/blog/golang-distributed-tracing-opentelemetry-based-observability/">Golang Distributed Tracing - OpenTelemetry Based Observability -</a></li><li><a href="https://javascript.plainenglish.io/9-best-distributed-tracing-tools-for-developers-185e415b7101">9 Best Distributed Tracing Tools for Developers</a></li><li><a href="https://python.plainenglish.io/opentelemetry-in-python-a-full-guide-98fef9b500a1">OpenTelemetry in Python — A Full Guide</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74390e1a400c" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/deploying-serverless-framework-on-aws-amplify-74390e1a400c">Deploying Serverless Framework on AWS Amplify</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[32 Pumpkins: what on earth to do with a commercial pumpkin patch after October]]></title>
            <link>https://tobinc.medium.com/32-pumpkins-what-on-earth-to-do-with-a-commercial-pumpkin-patch-after-october-c423c4dff540?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c423c4dff540</guid>
            <category><![CDATA[food]]></category>
            <category><![CDATA[inspiration]]></category>
            <category><![CDATA[cooking]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Tue, 27 Dec 2022 16:33:51 GMT</pubDate>
            <atom:updated>2022-12-27T16:33:51.524Z</atom:updated>
            <content:encoded><![CDATA[<p>Obligatory recipe over-the-top preamble all about me: Each October I help out at my <a href="https://www.facebook.com/dgwaltonandson">friend’s pumpkin patch</a> on <a href="https://goo.gl/maps/noJdqi6AsmJc9Wz38">World’s End Lane near Aylesbury</a>, selling pumpkins, chatting to customers, etc. Being active outside all day and chatting is fun and pleasantly different to a desk with Slack. <a href="https://d2ud33bruba52j.cloudfront.net/">I knocked up this app</a> so people could identify what they are picking from the vines. After each season, we come back to London with many many pumpkins.</p><p>If just left alone (inside or outside), the pumpkins seem to last perfectly until about the following May when they suddenly start to go gooey and clearly want to be planted. A lot of the flavours are quite similar so one quickly gets bored of eating them — we have put a lot of effort into vary different flavour combinations.</p><p>Here are the recipes I’ve tried so far with the pumpkin variety, along with a photo of the breed and my thoughts as someone with no official knowledge of plants except handling a lot of pumpkins. If you don’t know what you have, just match it to a photo below. Tom tells me next year there will double the varieties so…watch this space!</p><h3>Jack O Lantern</h3><figure><img alt="Jack o lantern" src="https://cdn-images-1.medium.com/max/1024/1*Xp0Mmc-HPOnCEfErlqjygg.jpeg" /></figure><p>These are not very good for eating. They seem to have been bred to have a very thin, spongy flesh with a large hollow (great for carving!), and have a bitter-er taste.</p><h3>Spaghetti Squash</h3><figure><img alt="2 Spaghetti Squashes" src="https://cdn-images-1.medium.com/max/1024/1*joJF98Ez-s1MvE-uWZaWpA.jpeg" /></figure><p>OK not a pumpkin, but grows in a similar way. I cook these with bolognese, using the squash instead of spaghetti. Having grown up with stringy underboiled British vegetables I was kind of doubtful about the whole concept, but this technique works tremendously 🙌</p><h4>Method</h4><ol><li>Chop squash in half along its length. If it’s older, it can have a bulletproof skin and chopping needs some aggression.</li><li>Scoop seeds out. I can’t remember if I tried to eat these seeds but they don’t stand out in my mind so perhaps not.</li><li>Place both halves of the squash open side up into a deepish tray; put like 1cm of water in the tray, and roast at 180C for 45mins — 1hr (really really variable tbh you just have to keep poking the flesh).</li><li>Make a bolognese sauce. I use <a href="https://www.facebook.com/dgwaltonandson">Church Farm’s Beef</a> as well cos it’s delicious. For lamb, guess what I also use <a href="https://www.facebook.com/dgwaltonandson">Church Farm’s Lamb</a>.</li><li>When the squash is cooked (a fork should easily pierce the flesh — the skin might still be solid), scraggle the fork around on the inside of the halves. This should suddenly turn the flesh into a bowl of soft tasty spaghetti.</li></ol><p>I’m not even kidding:</p><figure><img alt="Spaghettified spaghetti squash" src="https://cdn-images-1.medium.com/max/1024/1*6rOIE5F6bkc9sNplbFIyrg.jpeg" /></figure><h3>Delicata Squash</h3><p>Mm this is now 2 squashes and 1 non-pumpkin recipe…misleading title.</p><figure><img alt="Malwatered delicata squash" src="https://cdn-images-1.medium.com/max/1024/1*f6R2mQ8AnMnSt950XZyMwg.jpeg" /></figure><p>Due to the extremely hot summer in the UK this year, the Delicata squashes ended up a bit stunted and small. (see me for size) Although I imagine this created a bit more concentrated flavour.</p><figure><img alt="Wielding a squash" src="https://cdn-images-1.medium.com/max/1024/1*P-AaYZfmVjuVorf85ENXgg.jpeg" /><figcaption>Delicata squash with me for size</figcaption></figure><p>They have the most wonderful nutty and earthy flavour which permeates a mouthful, whilst not being stodgy. After cooking (skin on) they retain some structure and colouring making for good presentation.</p><h4>Method</h4><ol><li>Chop lengthways and scoop out the seeds. I used 3 small for this.</li><li>Follow <a href="https://dishingouthealth.com/wprm_print/12493">this recipe which turned out excellently</a>.</li></ol><figure><img alt="Delicata Squash Salad deliciousness" src="https://cdn-images-1.medium.com/max/1024/1*YhF1eJA-4UMmsKAQbBoAMw.jpeg" /><figcaption>Delicata squash in a most delicious format</figcaption></figure><h3>Giant Pink Banana</h3><figure><img alt="Giant Pink Banana" src="https://cdn-images-1.medium.com/max/1024/1*j7Oe4Bk_H9bAtXEIQtqdBA.jpeg" /><figcaption>Giant Pink Banana in its natural habitat</figcaption></figure><p>Up to 2 squashes, no pumpkins, and 1 banana — definitely fake news.</p><p>These are huge with a lot of flesh; however it seems to be mostly water and will massively shrink when cooked. They have a strong structure and will happily sit in the fridge and get thrown around without problem. The skin appears pretty tough so I didn’t try to cook it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a1sBT8UWVQpI6NI9JsiGlQ.jpeg" /><figcaption>Giant Pink Banana being processed</figcaption></figure><p>There isn’t a huge flavour so I found that this works well in long cooked curries in place of potatoes. The long cook lets the pieces shrink down so you can fit a whole banana in, and the pieces maintain bite and won’t disintegrate no matter how long you cook them and stir.</p><h3>Marina di Chioggia</h3><figure><img alt="Marina di Chioggia" src="https://cdn-images-1.medium.com/max/1024/1*q4scpfVZ_c8r5Zm3ht68EQ.jpeg" /><figcaption>Marina di Chioggia on its vine</figcaption></figure><p>Something we have noticed is that green pumpkins have been bred for flavour and flesh, vs orange pumpkins which have been bred to be orange.</p><p>As such, the flavour of this pumpkin is outstanding. Even when I first cut it you could tell from the smell (fresh, strong earthy and nutty, slightly moist but firm feel to the flesh), and colour (richness and depth, along with a beautiful variegation).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Smn93CftJ4UFr3JcLxgcpA.jpeg" /></figure><p><a href="https://georgeats.com/recipes/spice-roasted-pumpkin-with-haloumi-pomegranate-and-herb-sauce/#recipe">This is the guilty recipe</a>, my wonderful partner Hannah found it and the addition of preserved lemons is just amazing. It calls for “Kent Pumpkin” however works amazingly with this. The key difference I have found is that the pumpkin needs to be cooked for like 45mins at 180C then another &gt;1hr lower in the over to dry the chunks out. This creates a fabulous gooeyness to the outside and stops the salad getting watery (just look at the skin texture below). I put it on a small bed of green salad leaves which adds something I’m sure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5K9UsZIIuX4Uf4nli9brDA.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*dXr_zf6uGgR2YKY1Gb3A9Q@2x.jpeg" /></figure><h3>Harlequin, Acorn Squash, Table King</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*YGcrUECoqZCwrN2wzbUN7g@2x.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*6lpq0G5gzFZSkpoP23BRIQ@2x.jpeg" /></figure><p>One of these creates enough flesh for 2 people as part of meat and 2 vege, just a tasty accompaniment for a single meal. They bake to create a nutty and earthy flavour, but not as strong as above. The seeds are especially delicious when roasted.</p><h4>Method</h4><ol><li>Chop in half lengthwise, notch out the stalk, and nip the tip (if you bite the tip it will hurt)</li><li>Scoop out the seeds and stringy flesh. Put them in a sieve and rinse/stir so the seeds are free.</li><li>Chop the halves into longer thinner pieces with more surface area to transport the delicious sauce.</li><li>Make the delicious sauce: olive oil, lots of salt, sage (dried is easier, fresh is tastier)</li><li>Toss the pumpkin pieces in the delicious sauce bowl and thoroughly cover. Leave a little sauce in the bottom of the bowl.</li><li>Put the pumpkin onto an oven test and bake for around 30 mins at 180C or until the skin and flesh is triggering your eating instinct.</li><li>Put the seeds into the remaining mix and add to the oven tray for the last 10 mins of cooking. These should go a bit crispy and taste amazing.</li><li>For ultra laziness this pumpkin can be cooked completely whole with no preparation.</li></ol><h3>Crown Prince and Muscade De Provence</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*Xu3Lc3l0F3MZB_XpXN8LQw@2x.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*OOfTft2MvOL4r0r0uKNb4g@2x.jpeg" /></figure><p>Soup. Lots and lots of soup.</p><p>These have a very thick amount of flesh with minimal interior waste. The flesh is dense and tasty, and the pumpkins are large. This makes them good for soup as we can easily divide up remaining soup to the freezer, and it does not need to be bulked up with stodge. There are unlimited pumpkin soup recipes online so if you find yourself with a Crown Prince or Muscade, just find any recipe and adapt it. I tried to make pumpkin gnocchi but the water content made them extremely wet, requiring a lot of flour which ruined the flavour.</p><h3>Patti Pan</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*-ET1VRqmFHpCXkVKmniwFQ@2x.jpeg" /></figure><p>These are delicate and delicious – but only in June. By October they have a rock solid exterior and starting to get sad inside. They are very similar to courgette in my opinion and thus can be substituted in any recipe calling for courgette. We made a lovely salad gently frying chunks with courgette, olive oil, and salt.</p><h3>Turks turban</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*CFGewbVWpcs68JzCmCY5kQ@2x.jpeg" /></figure><p>These look pretty fab!! We haven’t tried eating one yet but hear good things – watch this space.</p><h3>Epilogue</h3><p>We continue to explore new recipes for the different varieties and I’ll keep adding the good ones.</p><p>The tiny pumpkins we have never tried to eat but they do look pretty.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c423c4dff540" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Side Hustle Tech: Building Hardwhere]]></title>
            <link>https://awstip.com/side-hustle-tech-building-hardwhere-6762dabd5847?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/6762dabd5847</guid>
            <category><![CDATA[google-business]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[ionic]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[local-seo]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Wed, 24 Aug 2022 14:57:56 GMT</pubDate>
            <atom:updated>2022-09-01T13:02:05.397Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Opinion:</strong> the best method to stay up to date on new and updated technology is to build something with it. The flipside is the such side projects are never completed and never get the use they might deserve.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qky1e1nheSLtispGGEyJBw.png" /></figure><p>I have forced myself to stop building and to finally publish <a href="https://hardwhere.co.uk/">Hardwhere</a>. The product concept is handy but a bit inflexible::</p><ol><li>Create a simple location based listing for your high street store</li><li>Take a photo of your shop shelves</li><li>Use AI to identify products and write e-commerce listings</li><li>Immediately upload to the <a href="https://hardwhere.co.uk/about">Hardwhere </a>website and <a href="https://merchants.google.com/">Google’s Free Local Product Listings</a>; shop and product pages are published with strong SEO</li><li>Watch your device for reservation request push notifications</li><li>Authorise payment for reservations up front and only capture if the person comes to the shop and takes the product</li></ol><p>I chose DIY hardware first because the AI recognises these items reliably; however the system does work very well on anything with text on a label.</p><p>I learnt a lot of funky techniques building this so thought it could be an interesting read.</p><h4>Components</h4><p>A device app is used to take photos and manage a user’s account. The backend is all AWS services within free tier and $1k startup credits, managed with Serverless Framework free dashboard tier. Customers access a NextJS website and all auth data is kept within their browser. Product searching is done against Opensearch.</p><h3>Technologies</h3><h4><a href="https://ionicframework.com/">Ionic Framework</a></h4><p>A super simple method to run Typescript web apps on a mobile device, with access to the device akin to a native app. Furthermore, I could build an app for <a href="https://apps.apple.com/us/app/hardwhere-shop/id1586334435?platform=iphone">App Store</a> and <a href="https://play.google.com/store/apps/details?id=uk.co.boffinsridge.hardwhere&amp;gl=GB">Play Store</a> simultaneously. At some point through the project, Ionic upgraded and then brought in Capacitor so I switched over easily by deleting and re-creating with whatever the CLI at the time was. The actual business logic TS was simply copied over each time. When I started, Ionic was only available with Angular and PhoneGap/Cordova via CLI. If I started again (again), then I’d probably use React and the Ionic remote build service and deployments.</p><p>I did the day to day development in Chrome on localhost which supported most of the required APIs. For debugging at native level I used <a href="https://developer.android.com/studio">Android Studio</a> and <a href="https://developer.apple.com/xcode/">Xcode</a>; this required some learning of enough Android-centric Java / Gradle and Swift / Pods to get by (yes <a href="https://stackoverflow.com/">Stack Overflow</a>!).</p><p><strong>Useful Plugins</strong></p><p>(There are so many to try out!)</p><p><a href="https://capacitorjs.com/docs/apis/camera">@capacitor/camera</a></p><p>Easily access the device’s front and back cameras, or saved photos on the device. The user will be prompted to allow permissions and can edit the photo before it is passed back to your code. During development, this will simply cause the file upload window to show. It seemed to have some unreliability with file paths so I set it to operate with base64 strings which have been very reliable. The photo is always a .jpeg from what I have seen (iOS + Android).</p><pre>    Camera.getPhoto({<br>        quality: 100,<br>        allowEditing: true,<br>        resultType: CameraResultType.Base64,<br>        promptLabelHeader: &quot;Where from?&quot;,<br>        promptLabelPhoto: &quot;Gallery&quot;,<br>        promptLabelPicture: &quot;Camera&quot;,<br>    })</pre><p>Actually uploading the image is straightforward by POSTing the image to <a href="https://docs.aws.amazon.com/AmazonS3/latest/userguide/PresignedUrlUploadObject.html">S3 with a signed URL</a>.</p><p><a href="https://capacitorjs.com/docs/apis/geolocation">@capacitor/geolocation</a></p><p>A quick way to find the user’s latitude and longitude instead of them typing in their current address. The user does have to positively allow permission in app though. The code is pretty much the same as the ‘normal’ browser method and development is straightforward. I found on iOS the module could just never resolve or reject, creating a permanently awaited Promise. My hacky solution is below.</p><pre>const waiter = setTimeout(() =&gt; {<br>       throw new Error(&quot;Geolocation timeout&quot;);<br>}, 6000);<br>const { coords } = await Geolocation.getCurrentPosition({<br>   enableHighAccuracy: true,<br>   timeout: 5000,<br>});</pre><p>For rough location, I used the <a href="https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-cloudfront-headers.html#cloudfront-headers-viewer-location">CloudFront IP based location service</a> just called via API Gateway which returns the header data if pinged (this could probably be done more elegantly though using mapping templates or Lambda Urls). Security is handled using signed IAM requests (more below).</p><pre>exports.handler = async (event) =&gt; ({<br>    statusCode: 200,<br>    headers: {<br>        &quot;Access-Control-Allow-Origin&quot;: &quot;*&quot;,<br>    },<br>    body: JSON.stringify({<br>        country: event.headers[&quot;CloudFront-Viewer-Country&quot;] || null,<br>        lat: event.headers[&quot;CloudFront-Viewer-Latitude&quot;] || null,<br>        lng: event.headers[&quot;CloudFront-Viewer-Longitude&quot;] || null,<br>        postCode: event.headers[&quot;CloudFront-Viewer-Postal-Code&quot;] || null,<br>    }),<br>});</pre><p><a href="https://capacitorjs.com/docs/apis/splash-screen">@capacitor/splash-screen</a></p><p>This is pretty much a defacto plugin; the Ionic asset compilation cli commands are excellently and I literally only had to supply 1 logo file and 1 splashscreen file. I’ve noticed launching on Android, the Capacitor logo is shown ever so briefly before Hardwhere’s splashscreen though.</p><p><a href="https://ionicframework.com/docs/v3/native/qr-scanner/">@ionic-native/qr-scanner</a></p><p>I needed an easy way to link user’s Manager accounts under a parent Collective entity. The uuid is displayed with a QR and the other device can scan it. This plugin was super confusing and still isn’t fully reliable. The plugin renders the camera image on a layer <em>behind </em>the Ionic app. The idea is that you can make the app backdrop go transparent then easily add any kind of overlay and buttons. This was a bit of trial and error, I used this to hide the relevant elements.</p><pre>document<br>.querySelector(&quot;app-edit-collective&quot;)<br>.parentElement<br>.style<br>.background = &quot;transparent&quot;;</pre><pre>document<br>.querySelector&lt;HTMLElement&gt;(&quot;app-edit-collective ion-content&quot;)<br>.shadowRoot<br>.querySelector&lt;HTMLElement&gt;(&quot;#background-content&quot;)<br>.style.background = &quot;transparent&quot;;</pre><pre>document<br>.querySelector(&quot;ion-router-outlet&quot;)<br>.style.display = &quot;none&quot;;</pre><pre>document<br>.querySelector&lt;HTMLElement&gt;(&quot;app-tab3&quot;)<br>.querySelector&lt;HTMLElement&gt;(&quot;ion-content&quot;)<br>.shadowRoot<br>.querySelector&lt;HTMLElement&gt;(&quot;#background-content&quot;)<br>.style<br>.background = &quot;transparent&quot;;</pre><p>For some unknown reason, once everything was working, I upgraded some packages and it suddenly stopped displaying the camera image on iOS real devices.</p><p>The plugin happily returns the scanned text string as JSON when it resolves. The permission can be shared with the regular camera plugin.</p><p><a href="https://ionicframework.com/docs/v3/native/device/">@ionic-native/device</a></p><p>This is used to identify when the app is running in a simulator, in browser development, or in the real environment. Useful for turning off some plugins (e.g. the geolocation can be skipped if running in Android Simulators), and generating device identifiers for debugging sessions.</p><h4>Debugging Ionic</h4><p>Logging in the browser is great but the simulators and devices have a real knack on producing totally unexpected behaviour due to permissions, data availability, etc.</p><p>Both platforms offer great local debugging. Android Studio and Xcode can launch the Ionic app directly onto a real device via USB cable and print stringified logs from the device. Note iOS can only be launched from MacOS but Android can be launched from Windows, MacOs, and Linux. A running device can also be connected to via Chrome (or Safari on MacOS) using the remote debugging developer tools. This has the advantage of being able to inspect elements, classes, and expand formatted console logs.</p><p>For real world, log shipping techniques are used to send the equivalent logs directly to CloudWatch. There is a free tier which seems enough for now (5GB per month). The requests are signed using the user’s Cognito Identity and sent to a logstream named for their Cognito username (or device id). Note the user can opt out at any time and/or request deletion within the app.</p><p>I had a dig around aws-amplify npm packages and discovered an API for CloudWatch to have a plugin for auto-shipping logs. The AWS SDK / CloudWatch library however is huge (perhaps aws-sdk v3 solves this? ). Requests to CloudWatch have to be AWS-v4 signed, and aws-amplify has a phenomenal inclusion which is the ability to sign IAM REST requests to any URL:</p><pre>// Amplify Config<br> API: {<br>    region: &quot;eu-west-2&quot;,<br>    endpoints: [<br>        {<br>            name: &quot;Logger&quot;,<br>            service: &quot;logs&quot;,<br>            endpoint: &quot;<a href="https://logs.eu-west-2.amazonaws.com/">https://logs.eu-west-2.amazonaws.com/</a>&quot;,<br>        },<br>    ],<br>},</pre><pre>// Use in code<br>API<br>.post(&quot;Logger&quot;, &quot;&quot;, {<br>    headers: {<br>        &quot;X-Amz-Target&quot;: &quot;Logs_20140328.PutLogEvents&quot;,<br>        &quot;Content-Type&quot;: &quot;application/x-amz-json-1.1&quot;,<br>    },<br>    body: {<br>        logEvents,<br>        logGroupName: this.logGroupName,<br>        logStreamName: this.logStreamName,<br>        sequenceToken: this.sequenceToken,<br>    },<br>})<br>.then(({ nextSequenceToken, rejectedLogEventsInfo }) =&gt; {<br>    this.sequenceToken = nextSequenceToken;<br>})</pre><p>There’s some fiddly bits like max event size, max entries, auth refresh, etc which need to be worked out.</p><pre>private extractSendableLogs = (): LoggedEvent[] =&gt; {<br>    const sendables = [];<br>    let remainingSize = AWS_CLOUDWATCH_MAX_BATCH_EVENT_SIZE;</pre><pre>while (<br>        remainingSize &gt;<br>            AWS_CLOUDWATCH_MAX_EVENT_SIZE +<br>                AWS_CLOUDWATCH_BASE_BUFFER_SIZE &amp;&amp;<br>        !!this.eventStack.length<br>    ) {<br>        const event = this.eventStack.shift();<br>        remainingSize -= new TextEncoder().encode(event.message).length;<br>        sendables.push(event);<br>    }</pre><pre>return sendables;<br>};</pre><h4>Deploying Ionic</h4><p>I followed Josh Morony’s fantastic guides for building and deploying to <a href="https://www.joshmorony.com/deploying-capacitor-applications-to-ios-development-distribution/">iOS App Store</a> and <a href="https://www.joshmorony.com/deploying-capacitor-applications-to-android-development-distribution/">Android Play Store</a>. I bought an Apple Developer Account ($79) and think Google was free (or maybe £30?). Hardwhere Shop is now listed on the <a href="https://apps.apple.com/us/app/hardwhere-shop/id1586334435?platform=iphone">App Store</a> and <a href="https://play.google.com/store/apps/details?id=uk.co.boffinsridge.hardwhere">Play Store</a>.</p><h3>Google Maps =&gt; AWS Location Service</h3><p>The first versions of the browser pages used the Google Maps but I struggled to find an easy to use React npm package, there are a lot of similar ones. Within the Ionic app, I tried <a href="https://github.com/ionic-team/ionic-native-google-maps/blob/master/documents/README.md">@ionic-native/google-maps</a> and created a complex switching class to render the native package on device, and an npm js package whilst developing in browser.</p><p>The API Key was restricted to the hardwhere.co.uk domain so browser requests were fine but requests within the Ionic app are made from localhost domain on Google and I could never work out what the iOS domain was so the key had to be unrestricted.</p><p>And then AWS brought out the Location Service. MVP rules would suggest don’t touch it but the benefits were strong: only uses AWS credits, can use native IAM authentication in Ionic and browser, and uses <a href="https://maplibre.org/">open source </a><a href="https://maplibre.org/">maplibre</a> with huge developer base and straightforward React packages. There was only one hiccup where a resource path randomly changed. Permissions were as simple as adding to the user’s IAM Role (the referer condition is superfluous), importing createMap from <a href="https://www.npmjs.com/package/maplibre-gl-js-amplify">maplibre-gl-js-amplify</a>, and configuring Amplify.</p><pre>// serverless.yaml<br>  LocationPolicy:<br>    Type: AWS::IAM::Policy<br>    Properties:<br>      PolicyName: Places-Search<br>      Roles:<br>        - !Ref RoleCustomerAuthed<br>        - !Ref RoleCustomerUnAuthed<br>      PolicyDocument:<br>        Version: &quot;2012-10-17&quot;<br>        Statement:<br>          - Effect: Allow<br>            Action:<br>              - geo:SearchPlaceIndexForText<br>              - geo:SearchPlaceIndexForPosition<br>              - geo:SearchPlaceIndexForSuggestions<br>            Resource:<br>              - arn:aws:geo:*:*:place-index/${sls:stage}-places<br>            Condition:<br>              StringLike:<br>                aws:referer:<br>                  - <a href="http://localhost:*">http://localhost:*</a><br>                  - <a href="https://${param:domain}*">https://${param:domain}*</a><br>          - Effect: Allow<br>            Action:<br>              - geo:GetMap*<br>            Resource:<br>              - arn:aws:geo:*:*:map/${sls:stage}-maps<br>            Condition:<br>              StringLike:<br>                aws:referer:<br>                  - <a href="http://localhost:*">http://localhost:*</a><br>                  - <a href="https://${param:domain}*">https://${param:domain}*</a></pre><pre>// Amplify.configure</pre><pre>API: {<br>    region: &quot;eu-west-2&quot;,<br>    endpoints: [<br>        {<br>            name: &quot;Location&quot;,<br>            service: &quot;geo&quot;,<br>            region: irelandRegion,<br>            endpoint: `<a href="https://places.geo.eu-west-1.amazonaws.com/places/v0/indexes/$%7BplacesIndexName%7D/search%60">https://places.geo.eu-west-1.amazonaws.com/places/v0/indexes/${placesIndexName}/search`</a>,<br>        },<br>    ],<br>},</pre><pre>geo: {<br>    AmazonLocationService: {<br>        maps: {<br>            items: {<br>                [mapsName]: {<br>                    style: &quot;Default style&quot;,<br>                },<br>            },<br>            default: mapsName,<br>        },<br>        region: irelandRegion,<br>    },<br>},</pre><h4><a href="https://capacitorjs.com/docs/guides/deep-links">Deeplinks (Cordova plugin then native Capacitor)</a></h4><p>The <a href="https://ionicframework.com/docs/native/deeplinks">Cordova deeplinks plugin</a> worked quite well but was hard to test. The <a href="https://capacitorjs.com/docs/guides/deep-links">Capacitor Deeplink</a> made it incredibly easy as the internal app is loaded onto the requested URL which is read with activatedRoute snapshot, making browser development easy too. In my case I route on /deep/ and pull actions from the URL.</p><p>Setting up the registration with iOS and Android was a bit trickier as each provider has their method of signatures and authorising devices to load your app. It was important for this project as I used magic link sign in with Cognito. The requisite apple-app-site-association and assetlinks.json files could just sit in the Next public folder with a CloudFront configuration to cache them:</p><pre>- AllowedMethods: [GET, HEAD, OPTIONS]<br>  TargetOriginId: AssetBucket<br>  Compress: true<br>  PathPattern: .well-known/*</pre><h3>NextJS: SSR in Lambda</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IM1qnNFpM_-h-h7uHijQSg.png" /></figure><p>Some of the pages could be statically exported, but the dynamic marketplace aspect creates a huge amount of changeable pages. ISG would solve this with an ECS container (build and cache pages), but this was built with Lambda SSR as it is cheaper for development and was using an older version of Next. Therefore, CloudFront is used as the short term cache (60s) using query params and Lambda renders the page.</p><p>The exportPathMap property of next.config.js deals with selecting which pages to generate javascript vs html files in the export . Then the Lambda selects which page to pass incoming requests to with this code, using the <a href="https://github.com/serverless-nextjs/serverless-next.js/blob/master/packages/compat-layers/apigw-lambda-compat/lib/compatLayer.js">amazing </a><a href="https://github.com/serverless-nextjs/serverless-next.js/blob/master/packages/compat-layers/apigw-lambda-compat/lib/compatLayer.js">compatLayer code</a> before Serverless-Next.</p><pre>const reqResMapper = require(&quot;./compatLayer&quot;);<br>const routes = require(&quot;./routes.json&quot;);</pre><pre>const pageMap = routes.reduce((acc, { page, resource }) =&gt; {<br>    acc[resource] = require(`.next/serverless/pages${page}`);<br>    return acc;<br>}, {});</pre><pre>module.exports.handler = async (event) =&gt; {<br>    console.log(JSON.stringify(event));<br>    const { req, res, responsePromise } = reqResMapper(event);<br>    pageMap[event.resource].render(req, res);</pre><pre>return responsePromise;<br>};</pre><p>API Gateway was chosen instead of Lambda@Edge: easier to develop with; larger code bundles; cheaper execution; higher latency but not too important for this.</p><p>Handling the api route in Next was achieved at CloudFront level by sending all /api* requests to another API Gateway origin.</p><pre>// Serverless.yml top level</pre><pre>plugins:  <br>  - serverless-domain-manager</pre><pre>custom:  <br>  customDomain:<br>    domainName: ${param:domain}<br>    basePath: api   &lt;== consumes the /api in the path<br>    certificateName: ${param:domain}<br>    createRoute53Record: false<br>    endpointType: regional<br>    securityPolicy: tls_1_2<br>    apiType: rest<br>    enabled: false</pre><pre>// Within CloudFront Serverless Resources</pre><pre>Origins:<br>  - Id: API<br>    DomainName: !Sub ${ApiGatewayRestApi}.execute-api.${AWS::Region}.amazonaws.com<br>    CustomOriginConfig:<br>      OriginProtocolPolicy: https-only</pre><pre>CacheBehaviors:<br>- AllowedMethods: [&quot;DELETE&quot;, &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;, &quot;PATCH&quot;, &quot;POST&quot;, &quot;PUT&quot;]<br>  TargetOriginId: API<br>  ForwardedValues:<br>   Headers:<br>    - Access-Control-Request-Headers<br>    - Access-Control-Request-Method<br>    - Host<br>    - Origin<br>    - Authorization<br>   QueryString: true<br>   Cookies:<br>    Forward: none<br>  Compress: true<br>  PathPattern: api/*<br>  ViewerProtocolPolicy: https-only<br>  DefaultTTL: 0</pre><p>GetServerSideProps was used extensively to render search pages from query params, including location. The actual location proximity search is done with OpenSearch location parameters.</p><h4>Top level paths coerced into API Gateway</h4><p>For dynamically rendered routes which can’t be in /api (e.g. /sitemap.xml ) a corresponding route is created under /toplevel (e.g. /toplevel/sitemap ) and defined by the Serverless Functions:</p><pre>// Functions.yml<br>sitemap:<br>  handler: lambda/sitemap/index.handler<br>  environment:<br>    ES_DOMAIN_ENDPOINT: ${param:opensearchDomainEndpoint}<br>  layers:<br>    - !Ref SitemapperLambdaLayer<br>  package:<br>    patterns:<br>      - lambda/sitemap/*<br>  iamRoleStatements:<br>    - Effect: Allow<br>      Action:<br>        - es:ESHttpGet<br>        - es:ESHttpPost<br>      Resource: arn:aws:es:*:*:domain/*<br>  events:<br>    - http:<br>        method: GET<br>        path: toplevel/sitemap.xml<br>        cors: true</pre><pre>Origins:<br>- Id: APITopLevel<br>  DomainName: !Sub ${ApiGatewayRestApi}.execute-api.${AWS::Region}.amazonaws.com<br>  OriginPath: /api/toplevel &lt;== Can only add to the path<br>  CustomOriginConfig:<br>    OriginProtocolPolicy: https-only</pre><pre>CacheBehaviors:<br>- AllowedMethods: [&quot;DELETE&quot;, &quot;GET&quot;, &quot;HEAD&quot;, &quot;OPTIONS&quot;, &quot;PATCH&quot;, &quot;POST&quot;, &quot;PUT&quot;]<br>  TargetOriginId: APITopLevel<br>  ForwardedValues:<br>     Headers:<br>      - Access-Control-Request-Headers<br>      - Access-Control-Request-Method<br>      - Host<br>      - Origin<br>      - Authorization<br>    Compress: true<br>    PathPattern: sitemap.xml<br>    ViewerProtocolPolicy: https-only<br></pre><h3>Magic Link login on Ionic with Cognito</h3><p>Using email and password is a bit annoying on device native apps as they never seem to work with saved passwords. The preferred method is to bring in Social Login so I attempted with Google. This worked right until I tried in the simulator and seems like Google is detecting and blocking logins from Ionic not using their external SDK. Sign in with Apple had some strugs too with Ionic so I opted to remove those and go for passwordless flow.</p><p>The customAuthChallenge flow is used, and we do not need to verify email/phone number as by definition the user does have access to those. If the user enters a phone number they are sent an SMS from the createAuthChallenge lambda.</p><pre>createAuthChallenge:<br>  handler: lambda/createAuthChallenge/index.handler<br>  iamRoleStatements:<br>    - Effect: &quot;Allow&quot;<br>      Action:<br>        - sns:publish<br>      Resource: &quot;*&quot;<br>    - Effect: &quot;Allow&quot;<br>      Action:<br>        - ses:sendEmail<br>      Resource: &quot;*&quot;<br>  package:<br>    patterns:<br>      - lambda/createAuthChallenge/*<br>  events:<br>    - cognitoUserPool:<br>        pool: UserPool<br>        trigger: CreateAuthChallenge</pre><p>The lambda generates a OTC and appends to a URL which is sent to email / SMS. Took a while but this code puts the sender “Hardwhere” onto received SMSs.</p><pre>const { MessageId } = await sns<br>    .publish({<br>        Message,<br>        PhoneNumber,<br>        Subject,<br>        MessageAttributes: {<br>            &quot;AWS.SNS.SMS.SenderID&quot;: {<br>                DataType: &quot;String&quot;,<br>                StringValue: &quot;Hardwhere&quot;,<br>            },<br>        },<br>    })<br>    .promise();</pre><p>The device creates a CognitoUser whilst waiting for the challenge to continue. The deep link is needed to return the user to Hardwhere Shop from their SMS or Email client. There is the chance that the app is restarted or closed whilst backgrounded, so the current login session state has to be manually saved onto the device storage.</p><pre>Auth<br>.signIn(this.username)<br>.then(async (user) =&gt; {<br>    if (user.challengeName === &quot;CUSTOM_CHALLENGE&quot;) {<br>        await this.storage.set(SessionKey, user.Session);<br>    } <br>})</pre><p>And the deep link extracts the stored session string to reconstruct a new CognitoUser and CognitoUserPool which appeared to only work when coming from the amazon-cognito-identity-js package directly.</p><pre>this.username = this.activatedRoute.snapshot.queryParams.username;<br>this.passcodeOTP = this.activatedRoute.snapshot.queryParams.code;<br>const userPoolData = {<br>    UserPoolId: environment.userPoolId,<br>    ClientId: environment.userPoolClientId,<br>};<br>const Pool = new CognitoUserPool(userPoolData);<br>this.authingUser = new CognitoUser({<br>   Pool,<br>   Username: this.username,<br>});<br>this.authingUser.Session = await this.storage.get(SessionKey);</pre><h4>Browser</h4><p>The browser works great with all the Social Sign ons using Cognito’s in built connections, so we have Facebook, Google, and Apple with full page redirects. The user can use email + password if they wish too.</p><p>All serverside rendered content is rendered in a null auth state; so spinners and placeholders carefully chosen. Only when the JS executes in the browser does it determine logged in status. This works great for export, caching, and preview of pages.</p><h3>Epilogue</h3><p>Thanks for reading, this is a bit of a brain dump of significant decisions and weird hacks to make stuff work.</p><p>Feel free to get in touch: tobin@hardwhere.co.uk</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6762dabd5847" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/side-hustle-tech-building-hardwhere-6762dabd5847">Side Hustle Tech: Building Hardwhere</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[SQS Dribbler Techniques]]></title>
            <link>https://awstip.com/sqs-dribbler-techniques-71d69ca9591c?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/71d69ca9591c</guid>
            <category><![CDATA[sqs]]></category>
            <category><![CDATA[sqs-lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[aws-lambda]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Thu, 16 Jun 2022 10:15:52 GMT</pubDate>
            <atom:updated>2022-06-17T08:24:38.893Z</atom:updated>
            <content:encoded><![CDATA[<p>A common problem with creating cloud infrastructure is integrating with traditional systems. Often the cloud infrastructure is capable of very high event rates, and the traditional system will have a much lower limit. The cloud infra will be designed for maximum scaling and parallelism, whilst the legacy vendor API could have a single DB with limited connections capability.</p><p>If anyone has any other methods please leave a message and I’ll add them here with attribution :)</p><figure><img alt="Minimum imagery I could get away with for this article." src="https://cdn-images-1.medium.com/max/324/1*cFGAufAww1YWHLCdbupxUg.png" /><figcaption>Minimum imagery I could get away with for this article.</figcaption></figure><h3>FIFO Queue, using messageGroupId</h3><p>Create a FIFO Queue with a subscribed lambda to consume messages. The FIFO Queue allows each message to be assigned a messageGroupId which can be any string value. All queued messages with the same messageGroupId are forced to be consumed sequentially — whilst a message is inFlight no other messages from that same messageGroupId will be sent to the Lambda service.</p><h4>Controlling Concurrency</h4><p>The Lambda service will poll SQS approximately 4 times per second whilst idle and no messages are returned. When messages are returned, the Lambda service will poll faster and invoke Lambda Functions. If all the queue messages contain the same messageGroupId , the polling will receive no messages whilst 1 message is inFlight . When the currently executing invoked Lambda Function completes (ignoring errors), the Lambda service calls deleteMessage for the consumed message, allowing the next message in the queue to be returned immediately. Thus, by sending all messages with the same messageGroupId the Lambda Function concurrency is forced to be 1.</p><p>To increase the Lambda Function execution concurrency to 2, the messages can be sent with 2 different messageGroupId alternating. This is true for any number of concurrent Lambdas required. This is because each stream (denoted by messageGroupId) will maintain its concurrency of 1.</p><p>If a Lambda Function invoke errors, the Lambda Service will not call deleteMessage and the message responsible will not be removed from inFlight . The message will remain inFlight until the visibilityTimeout on that message has expired. This will temporarily block the specific messageGroupId stream from receiving any messages.</p><p>The messageGroupId cannot be changed once a message has been sent into the FIFO Queue, so the concurrency can be hard to adjust via feedback if the concurrency should be controllable.</p><h3>Queue with Lambda reserved concurrency limit</h3><p>When a Lambda is subscribed to SQS, a few things happen behind the scenes. The Lambda Service acts as an intermediary and polls SQS approximately every 250ms with receiveMessage request specifying the maxReceivedMessages (presumably 1 if you are reading this article). When messages are returned, the Lambda Service invokes Lambda Functions with all of the returned messages (so 1 in this case). The Lambda Service immediately tries to receiveMessage again as the queue is now populated; and returns e.g. 1 message again.</p><p>If our Lambdas have no Reserved Concurrency, and the previously invoked Function is still executing, then another Lambda Function is invoked (we will see another Log Stream with a new container id) in parallel. This cycle will attempt to continue until an equilibrium is reached whereupon the number of concurrent Lambda Function containers is sufficient to process the messages as fast as the Lambda Service can receive them.</p><p>By applying a reservedConcurrency of 1 (or more) to the Lambda Functions, we can ensure that downstream services never exceed this. However this has the side effect that the Lambda Service will keep successfully receiving messages, but failing to invoke Lambda Functions as the concurrency limit is reached. This doesn’t register as failures because the Functions do not even execute, however this causes messages to not be deleted and simply sit in SQS until their visibilityTimeout times out, and the message can return to the back of the queue.</p><p>The benefit of this is allowing the concurrency to be adjusted on the fly; the downside is that the Queue becomes a mess and the monitoring becomes meaningless. The visibitlityTimeout must also be longer than the function execution time limit, and once messages have been made invisible, we must wait until one has timed out to return to the queue, resulting in randomly appearing long periods where there is no processing at all.</p><h3>Queue with non-subscribed, scheduled Lambda</h3><p>Instead of the Lambda Service, it is possible to call receiveMessage from within a Lambda Function, and control exactly how many messages are being processed concurrently from within the function code. The easiest way to trigger the Lamdbda Function is using Cloudwatch Events (<a href="https://awstip.com/setting-short-periodic-and-absolute-timeouts-in-aws-serverless-27dda2354de5">see this article for setting schedules faster than 1 minute</a>) and let the function pull messages until it can be triggered again. To control the concurrency on the fly, set a lambda environment variable with the desired maximum messages in flight, and describeQueue to establish if we are at this limit before receiving another message. The function can also control itself by setting its own environment variables, ready for the next invocation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71d69ca9591c" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/sqs-dribbler-techniques-71d69ca9591c">SQS Dribbler Techniques</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Setting short Periodic and Absolute timeouts in AWS & Serverless]]></title>
            <link>https://awstip.com/setting-short-periodic-and-absolute-timeouts-in-aws-serverless-27dda2354de5?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/27dda2354de5</guid>
            <category><![CDATA[scheduled-tasks]]></category>
            <category><![CDATA[timer]]></category>
            <category><![CDATA[step-functions]]></category>
            <category><![CDATA[aws]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 16:52:25 GMT</pubDate>
            <atom:updated>2022-06-15T06:49:36.811Z</atom:updated>
            <content:encoded><![CDATA[<p>Something which has caused me many headaches in AWS development is implementing a robust time based event control system. Distributed containers / AWS services work great until a single event needs to be fired — how do we decide which container triggers the event, or trigger a single API request to the ALB? What if we want to cancel a trigger?</p><p>I can’t find too much succinctly about this so please anyone with other strategies please message me and I’ll add them in with attribution.</p><h3>CloudWatch Events CRON Schedule</h3><p>This is the go to implementation in the AWS docs; simply setup a CloudWatch rule to trigger with a CRON Schedule, or a Rate. Subscribe a Lambda event-source to this and the Lambda will run on roughly the CRON schedule / rate — note that it is only accurate to within a few seconds.</p><pre>period1MinuteFunction:<br>  handler: functions/period1Minute/index.handler<br>  events:<br>    - schedule: cron(* * * * ? *)</pre><h4>Cost</h4><p>Practically nothing, just lambda invocation cost.</p><h4>Accuracy</h4><p>Minimum interval is 1 minute, accuracy within a few seconds (according to AWS). This is the recommended solution when triggering invocations with periods greater than 1 minute.</p><h3>CloudWatch Events Rate (multi rates)</h3><p>The Rate schedule available allows a minimum spacing of 1 minute between invocations. Unlike the CRON schedule, the Rate schedule can trigger off the minute. This means several Rate schedules can be setup and enabled at offset intervals to create a many times per minute overall trigger. Unfortunately this is a dynamic event and hard to model purely with Serverless so I used a combination of Serverless and function code.</p><h3>Step Function Wait tasks</h3><p>There is a handy <a href="https://aws.amazon.com/blogs/architecture/a-serverless-solution-for-invoking-aws-lambda-at-a-sub-minute-frequency/">AWS blog post</a> on triggering Lambdas at sub 1 minute frequency. The gist is to trigger a Step Function / State Machine every 1 minute using a CloudWatch Event Schedule, and within that Step Function use a series / loop of wait tasks to call a worker Lambda however many times required within that minute. The SF is likely to start at about the correct time so latency errors don’t compound, however a risk here that latencies in the system can cause sequential Lambda invokes to overlap.</p><h4>Performance</h4><p>Whilst putting together the design I found an awkward problem in that the Step Function must either:</p><ol><li>Trigger the worker Lambda synchronously and wait for it to finish, disrupting the timing accuracy considerably;</li><li>Trigger the worker Lambda asynchronously using a TaskToken and waiting for the putTaskSuccessResult from inside the lambda function.</li></ol><figure><img alt="The Step Function Wait Loop" src="https://cdn-images-1.medium.com/max/631/1*UjeMrzbKHkXfRW2nXMnX9A.png" /></figure><p>In both cases, the lambda function must provide the logic for determining if the loop is complete or not. A useful advantage is that the wait can be dynamic and each Lambda Invoke could calculate the next wait period.</p><h4>Cost</h4><p>Assuming a 10 second polling period of the worker Lambda Function: triggered every 1 minute, and invokes a lambda 5 times. The State Machine is triggered ~43200x per month, with 17 state transitions (start, invoke-choice-[wait|success] x 5, finish), costing ~USD18 per month for the SM.</p><h4>Better Variation: Dual Lambda Concept</h4><p>There is a variation on this where another Controller Lambda function is used instead of the State Machine. The Controller is triggered using Cloudwatch Events on a 1 minute schedule and configured to execute for 60s, and periodically invokeAsync the destination Lambda Function using a do-while-await loop in code. The Controller can execute with minimal memory (256MB) but does require running for 60000ms, costing ~USD4 per month. <em>Even with only 2 loops (a 30s </em><em>worker period) the SM cost is ~USD10 per month. </em>Therefore it’s probably better to use the Controller/Worker lambda pair instead of the State Machine/Lambda pair.</p><h3>SQS delay (FIFO) and self triggering</h3><p>A worker Lambda is subscribed to a FIFO queue which has a delay configuration equal to the desired trigger period. An external source sends a message to the queue containing a single number 1 . This triggers worker after the delay period (e.g. 2 seconds), which immediately sends a message to the same queue containing the invocation count++ ( 2 ), and the deduplicationId equal to the new invocation count (this can reset every 5 mins as the deduplication window rolls). To further enforce serial triggering, all the sent messages have the same messageGroupId (see my article on SQS dribbling).</p><p>The FIFO queue will ensure that each message is consumed exactly 1 time (no duplicate triggering) and control for deduplication e.g. if the Lambda fails, retries, and redelivers. Conversely, the FIFO queue can only have a single delay value per queue meaning each message cannot have its delay tailored and the SQS/Lambda latencies will cause the system to wander out of sync.</p><p>Because the Lambda (should) always successfully complete, the SQS message will be genuinely deleted and thus any poison messages should end up in your DLQ.</p><h3>SQS non-FIFO visibility timeout and persistent erroring</h3><p>A Lambda is subscribed to a SQS queue, with a visibilityTimeout set equal to the invocation period. A single message is sent to the queue, so that the worker lambda function is triggered. The worker eventually completes and then deliberately throws so that the message is not deleted. After the visibilityTimeout the message will reappear on the queue and be immediately received by the lambda.</p><h4>Thoughts</h4><p>This method hides any genuine errors emitted from the Lambda; it is tricky to differentiate between retryable errors (e.g. downstream api timeout) vs irrecoverable. The visibilityTimeout must be larger than the longest running time of the lambda, and it is a useful method to artificially reduce downstream rate limiting (see the dribbler article).</p><h3>SQS non-FIFO variable delay</h3><p>With a normal Queue, each message is able to have its own delay property set (up to 15 minutes). This means a loader lambda can be triggered every 15 minutes via CloudwatchEvents, which acts to load a Queue with every message needed to trigger the subscribedworker for the next 15 mins, each message having an appropriate delay. The loader can quickly stop execution and each message will appear at the calculated time.</p><h4>Thoughts</h4><p>This feels a bit clunky but is arguably very reliable; any worker errors will cause the message to be re-consumed after the visibilityTimeout and errors/successes will be propagated and reported correctly. The lambda must be set to 0 retries in case a message is consumed again whilst the first worker is still retrying.</p><h3>Route 53 health checks</h3><p>Route 53 will ping specified HTTP endpoints from up to 7 regions periodically to ensure that DNS entries are correctly operating. The ping period for each region can be configured as 10s or 30s. CloudFormation has a number in this field so perhaps future would allow for other values. There is no apparent way to configure the sequence of pings if multiple regions have been selected; the net result is a mish mash of pings.</p><p>This is a relatively low cost method however it is not very configurable.</p><h3>Absolute Events</h3><h4>Step Function Wait tasks</h4><p>As we saw earlier, Step Functions / State Machines have the ability for a Wait task to make the execution pause. The wait can be for a relative delay (10s above) or until an absolute timestamp. Furthermore, this timestamp can be set with an input variable, and includes milliseconds. For maximum flexibility, the payload can also contain the ARN of the triggered lambda.</p><pre>{<br>  &quot;StartAt&quot;: &quot;Wait&quot;,<br>  &quot;States&quot;: {<br>    &quot;Wait&quot;: {<br>      &quot;Type&quot;: &quot;Wait&quot;,<br>      &quot;Next&quot;: &quot;Lambda Invoke&quot;,<br>      &quot;TimestampPath&quot;: &quot;$.waitUntil&quot;<br>    },<br>    &quot;Lambda Invoke&quot;: {<br>      &quot;Type&quot;: &quot;Task&quot;,<br>      &quot;Resource&quot;: &quot;arn:aws:states:::lambda:invoke&quot;,<br>      &quot;OutputPath&quot;: &quot;$.Payload&quot;,<br>      &quot;Parameters&quot;: {<br>        &quot;Payload.$&quot;: &quot;$.event&quot;,<br>        &quot;FunctionName.$&quot;: &quot;$.functionName&quot;<br>      },<br>      &quot;End&quot;: true<br>    }<br>  }<br>}</pre><p>The State Machine is invoked from the triggering service using an event shaped below. A name is given to the execution which must be unique ish (e.g. customer number + month number).</p><pre>// Start Execution Data<br>{<br>  &quot;waitUntil&quot;:&quot;2022-06-13T16:42:00.562Z&quot;,<br>  &quot;event&quot;:{<br>    &quot;stuff&quot;: 1<br>  },<br>  &quot;functionName&quot;:&quot;echo&quot;<br>}</pre><pre>// End Execution Data (contents of $.Payload)<br>{<br>  &quot;statusCode&quot;: 200,<br>  &quot;body&quot;: &quot;{\&quot;stuff\&quot;:1}&quot;<br>}</pre><p>The executionArn is shaped predictably so the current wait task can be easily cancelled using a constructed executionArn.</p><pre>arn:aws:states:${AWS::Region}:${AWS::AccountId}:execution:${State Machine Name}:${Execution Name}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UJpmn9aEshyMLF9Njb1Wg.png" /></figure><h4>DynamoDB TTL + Stream</h4><p>Tables in DynamoDB have the ability to expire an Item at a specific time by setting the expire timestamp as a property of the Item. AWS does not guarantee the accuracy of these expires however suggests it will be within a few hours. A DDB Stream is setup to capture and publish change events; the expire event will captured as a REMOVE event, with the deleted Item contents within the event. The event can be easily published to a subscribed Lambda for processing.</p><h4>Thoughts</h4><p>It’s Free! The Stream has no extra cost if a table is already in use. Otherwise, a PAYG table is relatively cheap. AWS doesn’t guarantee much accuracy with this method, and the Item could take a few hours to expire. Of all the hacked methods, deleting the item means that it will be removed from the DDB and the only record of what the item was will be in CloudWatch.</p><h4>CloudWatch Events Schedule Rule</h4><p>The CRON allows for a single specific time to be set for a single rule to trigger. To trigger future dated events this is a cheap method, however it is only accurate to 1 minute. Having a lot of rules in the console makes this unwieldy for large dispersed events e.g. individual membership renewals.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27dda2354de5" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/setting-short-periodic-and-absolute-timeouts-in-aws-serverless-27dda2354de5">Setting short Periodic and Absolute timeouts in AWS &amp; Serverless</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adding Typescript Three.js to Wix Page]]></title>
            <link>https://tobinc.medium.com/adding-typescript-three-js-to-wix-page-a87a1fcfc7e1?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a87a1fcfc7e1</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[custom-component]]></category>
            <category><![CDATA[threejs]]></category>
            <category><![CDATA[wix]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Wed, 28 Apr 2021 14:13:39 GMT</pubDate>
            <atom:updated>2021-04-28T14:13:39.663Z</atom:updated>
            <content:encoded><![CDATA[<p>Wix allows for fast prototyping of web based startup ideas. It provides some really nice fully fledged systems and through the Editor it is possible to build advanced database (`Collection`) logic based flows.</p><p>I’ve found this flexibility trickier with the frontend which is based around either WYSIWYG click+ drag, or small snippets of raw HTML (e.g. for a colour picker). There is the possibility that your element can be exercised through including NPM Modules however Wix has blocked the heavy DOM manipulators (e.g. React, Three).</p><h4>Steps</h4><ol><li>Create a <strong>compatible</strong> Wix Site. There are business rules allowing this configuration so I will demonstrate with adding a page to my live site handyme.co.uk.</li><li>Create a simple, efficient development environment for generating the required files.</li><li>Create a custom component and embed it onto a new page in Wix</li><li>Integrate pushing data/events from standard Wix Buttons into the custom component</li><li>Listen to and act on event data coming out of the custom component</li></ol><h3>Create a compatible Wix Site</h3><h4>Paid Plan + Domain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xZ_AFBKjD7cB2fqcYnFjCw.png" /></figure><p>Just buy one of their signed up plans, they often have half price deals. The paid plan will normally include a free domain from a limited set of TLDs.</p><h4>Editor/Dev Mode</h4><p>A newly created site uses the ADI. First build your site as much as you can in here as it quickly gives you preset example layouts. Open <strong>Site</strong> &gt; <strong>Editor</strong> which allows a deeper level of configuration (spacing, text in random places, etc).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W0fRqtuSoRsu7mHcYDLxVw.png" /><figcaption>It’s a one way process</figcaption></figure><p>Then turn on <em>Dev Mode</em> to allow access to the code files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/950/1*el4FJObB9_qGyKXFDGXWyg.png" /></figure><p>An extra menu has appeared!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*XYdFsJavgPY0a05XnlLUug.png" /></figure><p><strong>Publish</strong> your site for posterity.</p><h3>Development environment</h3><p>I have opted for Typescript as the Three library is mega so the type prediction is super useful. A lot of my config bits have been default copied from the relevant sources i.e. Webpack, Typescript, etc.</p><pre>app/<br>├─ src/<br>│  ├─ index.html<br>│  ├─ index.ts<br>├─ package.json<br>├─ tsconfig.json<br>├─ webpack.config.js</pre><h4>File Contents</h4><pre>// package.json<br>{<br>  &quot;name&quot;: &quot;raised-bed-calculator&quot;,<br>  &quot;version&quot;: &quot;1.0.0&quot;,<br>  &quot;scripts&quot;: {<br>    &quot;start&quot;: &quot;webpack serve --open --mode=development&quot;,<br>    &quot;build&quot;: &quot;webpack --mode=production&quot;<br>  },<br>  &quot;author&quot;: &quot;Tobin Chew&quot;,<br>  &quot;devDependencies&quot;: {<br>    &quot;<a href="http://twitter.com/types/three">@types/three</a>&quot;: &quot;^0.127.1&quot;,<br>    &quot;html-webpack-plugin&quot;: &quot;^5.3.1&quot;,<br>    &quot;three&quot;: &quot;^0.128.0&quot;,<br>    &quot;ts-loader&quot;: &quot;^9.1.1&quot;,<br>    &quot;typescript&quot;: &quot;^4.2.4&quot;,<br>    &quot;webpack&quot;: &quot;^5.36.0&quot;,<br>    &quot;webpack-cli&quot;: &quot;^4.6.0&quot;,<br>    &quot;webpack-dev-server&quot;: &quot;^3.11.2&quot;<br>  }<br>}<br>// tsconfig<br>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;outDir&quot;: &quot;./dist/&quot;,<br>    &quot;noImplicitAny&quot;: false,<br>    &quot;module&quot;: &quot;es6&quot;,<br>    &quot;target&quot;: &quot;es6&quot;,<br>    &quot;allowJs&quot;: true,<br>    &quot;moduleResolution&quot;: &quot;node&quot;<br>  }<br>}</pre><p>Webpack config to create both the files to import into Wix, and the proving ground I can use locally.</p><blockquote>Note that I have used the Tag Nameraised-bed-calculator in multiple places to follow naming conventions. Anywhere you see this, replace it with what you are going to call your element. It can be anything reasonably unique sounding.</blockquote><pre>const path = require(&quot;path&quot;);<br>const HtmlWebpackPlugin = require(&quot;html-webpack-plugin&quot;);</pre><pre>module.exports = {<br>  entry: &quot;./src/index.ts&quot;,<br>  devtool: &quot;inline-source-map&quot;,<br>  devServer: {<br>    contentBase: &quot;./dist&quot;,<br>  },<br>  module: {<br>    rules: [<br>      {<br>        test: /\.tsx?$/,<br>        use: &quot;ts-loader&quot;,<br>        exclude: /node_modules/,<br>      },<br>    ],<br>  },<br>  resolve: {<br>    extensions: [&quot;.ts&quot;, &quot;.js&quot;],<br>  },<br>  output: {<br>    filename: &quot;custom-elements/<strong>raised-bed-calculator</strong>.js&quot;,<br>    path: path.resolve(__dirname, &quot;dist&quot;),<br>    clean: true,<br>  },<br>  plugins: [<br>    new HtmlWebpackPlugin({<br>      template: &quot;./src/index.html&quot;,<br>    }),<br>  ],<br>};</pre><p>Proving ground index.html into which Webpack will inject the transpiled TS code. The injected code contains a function to register the custom element `&lt;raised-bed-calculator&gt;&lt;/raised-bed-calculator&gt;`.</p><pre>&lt;html lang=&quot;en&quot;&gt;<br>  &lt;head&gt;<br>    &lt;meta charset=&quot;utf-8&quot; /&gt;<br>    &lt;style&gt;<br>      body {<br>        margin: 0;<br>      }<br>    &lt;/style&gt;<br>  &lt;/head&gt;<br>  &lt;body&gt;<br>    &lt;<strong>raised-bed-calculator</strong>&gt;&lt;/<strong>raised-bed-calculator</strong>&gt;<br>  &lt;/body&gt;<br>&lt;/html&gt;</pre><p>The output is a dist folder from which we can serve the index.html and copy the compiled custom element.</p><pre>app/<br>├─ dist/<br>│  ├─ index.html<br>│  ├─ custom-elements/<br>│     ├─ <strong>raised-bed-calculator</strong>.js</pre><p>Running npm start will compile the input index.html and launch a browser window with hot reload. npm run build will produce a minified version in the dist folder ready to upload.</p><p>For the rest of the project, we can stay within the index.ts file.</p><h3>Create and Embed a custom component</h3><p>From within the Velo Editor in Dev Mode</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NCUV4esG3eGhr3NNyEpCTg.png" /><figcaption>Add a Custom Element to the page</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5iRGl7vBrnzpOOU7lk5zQ.png" /></figure><p>Hit Choose Source and select Velo file then enter your chosen Tag Name and Create New.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*fZqdsITkFhijJUxwaBlDYQ.png" /></figure><p>Wix will create the appropriate folder structure and a default, example file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/524/1*i1RSurLxConYSdG82DnVLw.png" /></figure><p>Create a new .js file in the custom-elements folder and name it the same as your Tag Name. Open this file in the editor popup box below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*HQ_izcseSE2uoGb3GnMMlw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*19m0mGLVBdkOG31hzZs5bg.png" /></figure><p>Open the transpiled file in your dist folder. It might be quite large once Three is imported, and will all be on 1 line. Copy and paste its contents into this Wix file. Return to the Custom Component and check it’s updated (retry it if not).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/1*1O5AWoK4tW3uweAv5TPTgQ.png" /></figure><p>Publish your site and have a look at the page. It will take a moment to load and render as the Custom Components are loaded after the page fires its ready event.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nfUGM_TbCei9jf4xPkVOhQ.png" /></figure><p>For the above cube I used this index.ts which kind of works OK.</p><pre>import {<br>  BoxGeometry,<br>  Mesh,<br>  MeshBasicMaterial,<br>  PerspectiveCamera,<br>  Scene,<br>  WebGLRenderer,<br>} from &quot;three&quot;;<br>import { getParentDims, TagName } from &quot;./utils&quot;;</pre><pre>const createCanvas = () =&gt; {<br>  const { aspect, height, width } = getParentDims();<br>  const canvas = document.createElement(&quot;canvas&quot;);<br>  const scene = new Scene();</pre><pre>  const camera = new PerspectiveCamera(75, aspect, 0.1, 1000);</pre><pre>  const renderer = new WebGLRenderer({<br>    antialias: true,<br>    canvas,<br>  });<br>  renderer.setSize(width, height);</pre><pre>  const geometry = new BoxGeometry(10, 10, 10);<br>  const material = new MeshBasicMaterial({ color: 0x00aaaa });<br>  const cube = new Mesh(geometry, material);</pre><pre>  scene.add(cube);</pre><pre>  camera.position.z = 15;</pre><pre>  function animate() {<br>    requestAnimationFrame(animate);<br>    renderer.render(scene, camera);<br>  }<br>  animate();<br>  return canvas;<br>};</pre><pre>class RaisedBedCalculator extends HTMLElement {<br>  constructor() {<br>    super();<br>    console.log(&quot;RaisedBedCalculator constructor&quot;);<br>  }<br>  <br>  connectedCallback() {<br>    this.appendChild(createCanvas());<br>  }<br>}<br>customElements.define(TagName, RaisedBedCalculator);</pre><p>Coming soon; passing events and data freely between Three and Wix.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a87a1fcfc7e1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[AWS Amplify GraphQL with geo_point and Custom Resources: free Elasticsearch provider]]></title>
            <link>https://awstip.com/aws-amplify-graphql-with-geo-point-and-custom-resources-free-elasticsearch-provider-d1742fbc4ceb?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/d1742fbc4ceb</guid>
            <category><![CDATA[appsync]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Sun, 16 Feb 2020 13:07:00 GMT</pubDate>
            <atom:updated>2022-07-21T10:47:18.903Z</atom:updated>
            <content:encoded><![CDATA[<h3>AWS Amplify GraphQL with Geolocation and Custom Resources: free Elasticsearch provider</h3><h3>Situation</h3><ol><li>An Amplify project has been created with a GraphQL API</li><li>Schema contains at least one @model</li><li>You would like to implement a side-project-worthy low-cost search</li><li>Search will include location ( geo_point )</li></ol><p>Services within the AWS ecosystem have been carefully and wonderfully built to interact and consume each other very well. The Amplify CLI library is fantastic and incredibly well put together, with regular additions. Currently we can add @searchable to a a GraphQL definition which sets up the necessary backend (AWS Elasticsearch, DDB Trigger, etc).</p><h3>Problem</h3><p>For me there were 2 problems with using @searchable :</p><ol><li>There is a free tier that lasts about 1 month, then AWS ES costs $30/month regardless of use. Working on side projects that might not be touched for a month, this was unhelpful considering everything else spawned with Amplify is PAYG.</li><li>My barely-used AWS ES cluster one night just became unresponsive , it would not respond or load any stats into the AWS Console. I deleted it but it took a few days to disappear, through which I could not push my Amplify stack.</li></ol><h3>Solution</h3><ol><li>Use a dedicated Elasticsearch provider for Elasticsearch services. I chose <a href="https://bonsai.io/">Bonsai</a> as it has a genuinely free tier — ideal for side projects — and an easy to use browser console for direct queries.</li><li>Bridge it into AWS Appsync as an HTTP Datasource with Authorisation header</li><li>Create a DynamoDB Stream Trigger that propagates Item changes to Bonsai (just like with @searchable into AWS Elasticsearch)</li><li>Create GraphQL Schema Queries and Custom Resolvers</li></ol><h3>Setup Amplify Backend</h3><p>This article assumes a basic knowledge of using Amplify for a project already.</p><h4>Create a new project</h4><ol><li>Create a new project park_trees and link it with an AWS profile.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*eV4myvl-_6NToPmqZYv2YA.png" /></figure><p>2. Open the project and run amplify add api ; run through the process to add an auth too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMRmmY5xOvsMKu1-DAY6dQ.png" /></figure><p>3. Edit the Tree type in schema.graphql and add the Location type; this is a format that geo_point understands.</p><pre>type Tree @model {<br> id: ID!<br> species: String!<br> location: Location!<br> height: Float<br>}</pre><pre>type Location {<br> lat: Float!<br> lon: Float!<br>}</pre><p>Send this to the cloud with amplify push and generate the local types for maximum helpfulness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AEhopPSZfxK7FZz3eeDuFw.png" /></figure><p>For some reason my Amplify didn’t populate the API.ts file, so if this happens to you, fix it by running amplify codegen.</p><h4>Digesting the `./amplify` directory</h4><p>Cloudformation lists the 1 root stack and various nested stacks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gSoEniDv4CbViSIz2IZp2g.png" /></figure><pre>parktrees<br>├── apigraphql<br>|   ├── Tree<br>|   ├── CustomResources<br>├── authparktrees</pre><p>Each category of resource ( auth, function, etc) contains a nested Cloudformation stack and a parameters.json which allows custom &amp; additional parameters to be passed into the nested stack. Parameters defined here can Ref sibling resources within the root stack. The sibling resource names can be found by opening the generated root stack at amplify/backend/awscloudformation/nested-cloudformation-stack.yml</p><pre>parktrees<br>├── (1) parameters.json ── apigraphql<br>|                        ├── Tree<br>|                        ├── CustomResources<br>|<br>├── (2) parameters.json ── authparktrees</pre><h4>Example</h4><p>In this project the amplify/backend/auth/parktrees36c90b1a/parameters.json file can be edited to<em> </em>change some properties, and updated in the cloud with amplify push:</p><pre>&quot;emailVerificationMessage&quot;: &quot;Your verification code is {####}&quot;,</pre><p>Elements in the auth Cloudformation template file can also be updated! But beware, it can get overwritten when making changes using the CLI.</p><pre>`<em>amplify/backend/auth/parktrees36c90b1a/</em>parktrees36c90b1a-cloudformation-template.yml` </pre><p>The next step I find a little bit of a mindfuck but the API resource contains another level of nested CF stacks. There is an intimate relationship between the various stacks and 2 files:<br>- amplify/backend/api/graphql/stacks/CustomResources.json <br>- amplify/backend/api/graphql/parameters.json</p><p>Parameters defined in CustomResources.json will be automatically added to the AWS::Cloudformation:Stack resource’s parameters property in the apigraphql stack as Refs. This way, the same parameter names can be defined in the apigraphql parameters.json and Ref other project resources ( auth etc).</p><p>However, I haven’t found how to Ref sibling resources inside the apigraphql stack (it can be done using Export + Import). For example, I could not Ref the Tree table from CustomResources. If anyone can tell me please leave a comment!!</p><h4>Check out the provisioned Resources</h4><p>A DynamoDB table called Tree has been created from the Tree stack.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AZK9_fBHLQWS6NoI7AtUpA.png" /></figure><p>AppSync has an extensive GraphQL Schema and resolvers setup for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Dw7HI-4QPlEE8LI9TedPfg.png" /></figure><p>Find the GetTree resolver, it’s under Query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/403/1*EAx-iFX04Rk5lN1-unaHXQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3JqV07fP_nmf4nrxtzbWpQ.png" /><figcaption>Request mapping VTL template for Query.getTree</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6En36pyU7IwUiEWvMhYoKA.png" /><figcaption>Response mapping VTL template for Query.getTree</figcaption></figure><h3>ElasticSearch provider</h3><p>I chose <a href="https://bonsai.io/">Bonsai </a>because it has a very intuitive interface, web browser console to interact with the cluster, and offers a genuine free tier.</p><ol><li>Provision a new cluster</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6qd6UvCbiiTTWQXAgeqHA.png" /></figure><p>2. Find your credentials</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2Yb3zq4Rejh_qAyG9CeNIA.png" /></figure><pre>https://zx5dej31tt:5inkmy78lz@park-trees-medium-7535634961.eu-west-1.bonsaisearch.net:443</pre><pre>https://key:secret@cluster.eu-west-1.bonsaisearch.net</pre><p>Split this URL into its components:</p><pre>Key        zx5dej31tt                                               <br>Secret     5inkmy78lz                                               <br>BaseUrl    park-trees-medium-7535634961.eu-west-1.bonsaisearch.net  <br>Protocol   https</pre><h3>Create an HTTP Datasource</h3><p>Within the Resources block of the CustomResources.json template, add the custom AWS::AppSync::DataSource resource.</p><pre>// CustomResources.json<br>&quot;Parameters&quot;: {<br>  &quot;AppSyncApiId&quot;: {<br>    &quot;Type&quot;: &quot;String&quot;,<br>  },<br>  &quot;BonsaiEndpoint&quot;: {<br>    &quot;Type&quot;: &quot;String&quot;,<br>  }<br>},<br>&quot;Resources&quot;: {<br>  &quot;BonsaiDatasource&quot;:{<br>    &quot;Type&quot; : &quot;AWS::AppSync::DataSource&quot;,<br>    &quot;Properties&quot; : {<br>      &quot;ApiId&quot; :{<br>        &quot;Ref&quot;: &quot;AppSyncApiId&quot;<br>      },<br>      &quot;HttpConfig&quot; : {<br>        &quot;Endpoint&quot; : { <br>          &quot;Ref&quot;:&quot;BonsaiEndpoint&quot;<br>        }<br>      },<br>      &quot;Name&quot; : &quot;BonsaiElasticsearch&quot;,<br>      &quot;Type&quot; : &quot;HTTP&quot;<br>    }<br>  }<br>}</pre><p>And add theEndpoint as the Protocol + BaseUrl in the graphqlapi parameters.json. AppSync drops the Key and Secret from the URL so it doesn’t need to be added to the template (which is in GIT anyway.. )</p><pre>{<br>    &quot;AppSyncApiName&quot;: &quot;graphql&quot;,<br>    &quot;BonsaiEndpoint&quot;: &quot;<em>https://park-trees-medium-7535634961.eu-west-1.bonsaisearch.net</em>&quot;<br>}</pre><h3>Add Custom Schema + Resolvers for a Search Query</h3><p>Create a type in schema.graphql which can be queried, and a resolver to tell AppSync how to interact with Bonsai.</p><h4>Create Search Types</h4><p>Add the following to the end of the amplify/backend/api/graphql/schema.graphql file.</p><pre>input LocationInput {<br>  lat: Float!<br>  lon: Float!<br>}<br>input NearbyTreesInput {<br>  location: LocationInput!<br>  km: Int!<br>  limit: Int!<br>}</pre><pre>type Query {<br>  nearbyTrees(input: NearbyTreesInput!): NearbyTreesConnection!<br>}</pre><pre>type NearbyTreesConnection {<br> items: [NearbyTreeConnectionItem!]!<br>}</pre><pre>type NearbyTreeConnectionItem {<br> tree: Tree!<br> distance: Float!<br>}</pre><p>Note the type Query which will be combined with the rest of the Query types generated with the Tree @model by Amplify CLI. Now GraphQL clients can interact with the AppSync GraphQL API endpoint.</p><h4>Create the Resolvers</h4><blockquote>There are naming conventions to follow</blockquote><p>Add an AWS::AppSync::Resolver resource to the same CustomResources.json, match the FieldName to the schema.graphql type name, and the BonsaiDatasource Ref to the Datasource above.</p><pre>&quot;QueryNearbyTrees&quot;: {<br>   &quot;Type&quot;: &quot;AWS::AppSync::Resolver&quot;,<br>   &quot;Properties&quot;: {<br>    &quot;ApiId&quot;: {<br>     &quot;Ref&quot;: &quot;AppSyncApiId&quot;<br>    },<br>    &quot;DataSourceName&quot;: {<br>     &quot;Fn::GetAtt&quot;: [<br>      &quot;BonsaiDatasource&quot;,<br>      &quot;Name&quot;<br>     ]<br>    },<br>    &quot;TypeName&quot;: &quot;Query&quot;,<br>    &quot;FieldName&quot;: &quot;<strong>nearbyTrees</strong>&quot;,<br>    &quot;RequestMappingTemplateS3Location&quot;: {<br>     &quot;Fn::Sub&quot;: [<br>      &quot;s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/<strong>Query.nearbyTrees.req.vtl</strong>&quot;,<br>      {<br>       &quot;S3DeploymentBucket&quot;: {<br>        &quot;Ref&quot;: &quot;S3DeploymentBucket&quot;<br>       },<br>       &quot;S3DeploymentRootKey&quot;: {<br>        &quot;Ref&quot;: &quot;S3DeploymentRootKey&quot;<br>       }<br>      }<br>     ]<br>    },<br>    &quot;ResponseMappingTemplateS3Location&quot;: {<br>     &quot;Fn::Sub&quot;: [<br>      &quot;s3://${S3DeploymentBucket}/${S3DeploymentRootKey}/resolvers/<strong>Query.nearbyTrees.res.vtl</strong>&quot;,<br>      {<br>       &quot;S3DeploymentBucket&quot;: {<br>        &quot;Ref&quot;: &quot;S3DeploymentBucket&quot;<br>       },<br>       &quot;S3DeploymentRootKey&quot;: {<br>        &quot;Ref&quot;: &quot;S3DeploymentRootKey&quot;<br>       }<br>      }<br>     ]<br>    }<br>   }<br>  }</pre><p>Note the 2 filenames Query.nearbyTrees.re(q|s).vtl and create them in the empty directory amplify/backend/api/graphql/resolvers/ . The resolvers are written using Velocity Template Language; Amplify CLI generates resolvers for the @model types already in amplify/backend/api/graphql/build/resolvers/.</p><h4>The Request Resolver</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6dd0bb489a4e5760b3f4b22197e114f/href">https://medium.com/media/e6dd0bb489a4e5760b3f4b22197e114f/href</a></iframe><p><a href="https://docs.bonsai.io/article/94-connecting-to-bonsai">Bonsai docs require URL authentication</a>, however AppSync drops the User / Password from the URL. Therefore, explicitly add a Basic Auth header containing the Base64 encoding of the User and Password.</p><pre>Authorization: &quot;Basic eng1ZGVqMzF0dDo1aW5rbXk3OGx6&quot;</pre><p>Line 4 commits the cardinal sin of baking credentials into git’d code. To be honest I haven’t found an easy way of getting credentials into the VTL template at runtime:</p><ul><li>Lambda could be used as a bridge, get the credentials from AWS Secrets Manager and add the header in real time</li><li>Baked in read-only credentials and the Elasticsearch content is scoped down to Id + Location only</li><li>Send password with each request from the webapp</li><li>Send credentials through JWT claims</li><li>Map the VTL to an API Gateway HTTP proxy resource which adds a static Auth header and passes through the body</li></ul><p>The resolver object returned instructs AppSync to make a POST HTTP request to the resourcePath with the query body performing a few functions:</p><ol><li>Return all results</li><li>Filter for only results within distance</li><li>sort the results with lowest distance first</li><li>Applies a limit to the number of returned results (optional)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xfy2cNSRBmBGPqaP2a84Mw.png" /></figure><p>The AppSync console has fantastic intellisence and auto-fill so it’s definitely worth to edit and test resolvers in the console before committing.</p><h4>The Response Resolver</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b153b806b3d7f8bb450ead532c85a40a/href">https://medium.com/media/b153b806b3d7f8bb450ead532c85a40a/href</a></iframe><p>The resolver assembles the Elasticsearch results into a more palatable array of Trees with their distance. The Tree and distance properties are split up to preserve the type of Tree to keep Typescript happy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v8PQ8L3Sf1jgkvHIS2uYPg.png" /></figure><h3>Create Bonsai Index</h3><p>The AWS Elasticsearch is setup to auto-create indices, but Bonsai is not. Furthermore, an index has to explicitly be setup to use geo_point searching <em>before</em> <em>any</em> items are added. Elasticsearch has fantastic documention on how to create an index, but this is necessary for Tree.</p><pre>{<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;createdAt&quot;: {<br>        &quot;type&quot;: &quot;date&quot;<br>      },<br>      &quot;height&quot;: {<br>        &quot;type&quot;: &quot;float&quot;<br>      },<br>      &quot;id&quot;: {<br>        &quot;type&quot;: &quot;text&quot;<br>      },<br>      &quot;species&quot;: {<br>        &quot;type&quot;: &quot;text&quot;<br>      },<br>      &quot;updatedAt&quot;: {<br>        &quot;type&quot;: &quot;date&quot;<br>      },<br>      &quot;location&quot;: {<br>        &quot;type&quot;: &quot;geo_point&quot;<br>      }<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8vNHBqWC1GR6N32kQnzJhA.png" /></figure><h3>Propagating DDB changes to Bonsai Elasticsearch</h3><p>When @searchable is used, Amplify creates a Python Lambda function which propagates changes automatically. This Function is really well made so the code can be modified to work with Bonsai; the ancillary parts just need adding as Custom Resources. A DynamoDB Stream pushes item changes to the Lambda function which converts and forwards them to Elasticsearch Bulk API.</p><h4>Alternative methods</h4><ul><li>Use a Node Lambda using an NPM package</li><li>Use SNS triggers from DDB mapped to an API Gateway resource, which would contain another VTL to convert the SNS Message to Elasticsearch directly</li><li>Create a Mutation.updateBonsaiTree which maps to the Bonsai Endpoint and a custom resolver, and use SNS triggers from DDB mapped to the GraphQL Endpoint</li></ul><h4>Safely store the Connection String</h4><p>Unlike the VTL, create a Secrets Manager secret containing the connection details for Bonsai. It is just the string so it doesn’t need to be JSON (gotta save those Lambda CPU cycle GB-Sec $$).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1021/1*IEvvux0B3d4GZXHBU69Y4w.png" /></figure><p>The Secret Arn:</p><pre>arn:aws:secretsmanager:eu-west-2:123:secret:medium-bonsai</pre><h4>Create the Lambda Function</h4><p>Run amplify function add and amplify push without editing the source code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*ZAqb8NjoSGCnOPd5KqjGZQ.png" /></figure><h4>Add permission to interact with DDB Streams and get the Secret</h4><p>Once the DDBToBonsai function is created in the cloud, add a CustomResource Policy which allows access to the Tree DDB table (or any other tables this function will stream).</p><p>Find the DDBToBonsai stack Resource Logical Id in the nested-cloudformation-stack.yml file, and the DDBToBonsai nested stack itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FYIxXHPQzEnhL7Aw3hV6dQ.png" /><figcaption>The nested DDBToBonsai stack and it’s parent</figcaption></figure><p>For a shortcut, if not using the Secrets Manager, it is possible to add directly to the DDBToBonsaiExecutionRole — beware this would be overwritten if the Lambda is edited in Amplify CLI.</p><pre>&quot;ManagedPolicyArns&quot;: [<br>     &quot;arn:aws:iam::aws:policy/service-role/AWSLambdaDynamoDBExecutionRole&quot;<br>]</pre><p>The DDBToBonsai nested stack Output is accessible directly in the amplify/backend/api/graphql/parameters.json file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fIezZU-liX3vsp9VWjadbA.png" /><figcaption>parameters.json for apigraphql</figcaption></figure><pre>    &quot;DDBToBonsaiFunctionRole&quot;:{<br>        &quot;Fn::GetAtt&quot;: [<br>            &quot;functionDDBToBonsai&quot;,<br>            &quot;Outputs.LambdaExecutionRole&quot;<br>        ]<br>    }</pre><p>Create a suitable policy in CustomResources.json</p><pre>&quot;Parameters&quot;: {<br>  ...,<br>  &quot;DDBToBonsaiFunctionRole&quot;: {<br>   &quot;Type&quot;: &quot;String&quot;<br>  }<br>},<br>&quot;Resources&quot;: { <br>  ..., <br>  &quot;BonsaiFunctionPolicy&quot;: {<br>   &quot;Type&quot;: &quot;AWS::IAM::Policy&quot;,<br>   &quot;Properties&quot;: {<br>    &quot;PolicyName&quot;: &quot;main&quot;,<br>    &quot;PolicyDocument&quot;: {<br>     &quot;Version&quot;: &quot;2012-10-17&quot;,<br>     &quot;Statement&quot;: [<br>      {<br>       &quot;Effect&quot;: &quot;Allow&quot;,<br>       &quot;Action&quot;: [<br>        &quot;dynamodb:DescribeStream&quot;,<br>        &quot;dynamodb:GetRecords&quot;,<br>        &quot;dynamodb:GetShardIterator&quot;,<br>        &quot;dynamodb:ListStreams&quot;<br>       ],<br>       &quot;Resource&quot;: &quot;*&quot;<br>      },<br>      {<br>       &quot;Sid&quot;: &quot;10&quot;,<br>       &quot;Effect&quot;: &quot;Allow&quot;,<br>       &quot;Action&quot;: &quot;secretsmanager:GetSecretValue&quot;,<br>       &quot;Resource&quot;: {<br>        &quot;Fn::Sub&quot;: &quot;arn:aws:secretsmanager:eu-west-2:${AWS::AccountId}:secret:medium-bonsai&quot;<br>       }<br>      }<br>     ]<br>    },<br>    &quot;Roles&quot;: [<br>     {<br>      &quot;Ref&quot;: &quot;DDBToBonsaiFunctionRole&quot;<br>     }<br>    ]<br>   }<br>  }<br>}</pre><h4>Convert the DDBToBonsai Amplify Function to use Python</h4><p>Running amplify push will automatically run npm i in each registered function directory, zip the directory contents, and update-function-code in Lambda service. Therefore the function can use Python by updating the function cloudformation, and pretending to be node. Update DDBToBonsai-Cloudformation-Template.json and make sure to never change it with Amplify CLI. Delete all the files except package.json .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*GSsVRVLI4Nfefee9tAgr2A.png" /><figcaption>Changing Lambda Function to Python</figcaption></figure><p>The actual Python code itself is AWS’s baby and doesn’t have a license embedded; I am a little unsure if it’s allowed to be used so I will only show my changes (AWS feel free to get in touch — an opportunity to try one of the alternative methods listed!).</p><p>Main changes are setting the ES_ENDPOINT to directly use the Connection String, and DOC_TYPE = &#39;_doc&#39; . The Function must contain the Environment Variable DEBUG or the reference must be removed from the code.</p><pre>DEBUG = True </pre><pre>secretsClient = Session().client(service_name=&#39;secretsmanager&#39;,region_name=&#39;eu-west-2&#39;)<br>get_secret_value_response = secretsClient.get_secret_value(<br>            SecretId=&#39;arn:aws:secretsmanager:eu-west-2:818304461904:secret:medium-bonsai-BHiuhN&#39;<br>        )<br>ES_ENDPOINT = get_secret_value_response[&#39;SecretString&#39;]<br>DOC_TYPE = &#39;_doc&#39;</pre><h4>Subscribe the DDBToBonsai Function to DDB Stream</h4><p>Another Custom Resource! Use a AWS::Lambda::EventSourceMapping resource. To find the EventSourceArn Import the value Exported from its sibling the Tree Cloudformation stack.</p><p>Add to parameters.json underneath the DDBToBonsaiFunctionRole :</p><pre>    &quot;DDBToBonsaiFunction&quot;:{<br>        &quot;Fn::GetAtt&quot;: [<br>            &quot;functionDDBToBonsai&quot;,<br>            &quot;Outputs.Name&quot;<br>        ]<br>    }</pre><p>And in CustomResources.json</p><pre>&quot;Parameters:{ <br>  &quot;AppSyncApiId&quot;:{<br>    &quot;Type&quot;:&quot;String&quot;<br>  },<br>  ...,<br>  &quot;DDBToBonsaiFunction&quot;:{<br>    &quot;Type&quot;:&quot;String&quot;<br>  },<br>},<br>&quot;Resources&quot;:{<br>  ...,<br>  &quot;ESMTreeDDBtoBonsai&quot;:{<br>    &quot;Type&quot; : &quot;AWS::Lambda::EventSourceMapping&quot;,<br>    &quot;Properties&quot; : {<br>      &quot;Enabled&quot; : true,<br>      &quot;EventSourceArn&quot; : {<br>        &quot;Fn::ImportValue&quot;: {<br>          &quot;Fn::Join&quot;:[<br>            &quot;:&quot;,<br>            [<br>              {<br>                &quot;Ref&quot;:&quot;AppSyncApiId&quot;<br>              },<br>              &quot;GetAtt&quot;,<br>              &quot;TreeTable&quot;,<br>              &quot;StreamArn&quot;<br>            ]<br>          ]<br>        }<br>      },<br>      &quot;FunctionName&quot; : {<br>        &quot;Ref&quot;:&quot;DDBToBonsaiFunction&quot;<br>      },<br>      &quot;MaximumRetryAttempts&quot; : 0,<br>      &quot;StartingPosition&quot; : &quot;LATEST&quot;<br>    }<br>  }<br>}</pre><h3>Test it out</h3><p>Although the Tree model doesn’t have any @auth enabled, AppSync still requires some authentication to interact. There are a few methods but by far the easiest for testing is to change the Default Authentication type to API Key and create a New Key.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T44YmGZriAAGVU6M_OP4Gw.png" /><figcaption>Create an API Key</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rqVLNKpMyZNgGnaGF06c-g.png" /><figcaption>Within Queries, easy access is available</figcaption></figure><h4>Make a Tree</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tbv3oD-M_b5yMrzIAI-ELQ.png" /><figcaption>Make a tree</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BIcQHpnAqrYYo3BA_X8VtQ.png" /><figcaption>As stored in DDB</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wcFWLlN0DVSX1h2aC_Zwzg.png" /><figcaption>Searchable in Bonsai Elasticsearch</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vsrge6WvhmLW26qQB3V6CQ.png" /><figcaption>Get and List in AppSync (and therefore an App)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*puLignDFuZ91Dx6vPvmzLQ.png" /><figcaption>Searchable in AppSync with Geo distance!</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d1742fbc4ceb" width="1" height="1" alt=""><hr><p><a href="https://awstip.com/aws-amplify-graphql-with-geo-point-and-custom-resources-free-elasticsearch-provider-d1742fbc4ceb">AWS Amplify GraphQL with geo_point and Custom Resources: free Elasticsearch provider</a> was originally published in <a href="https://awstip.com/">AWS Tip</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Automatically Add Partitions to AWS Glue using Node/Lambda Only]]></title>
            <link>https://medium.com/cloud-native-daily/automatically-adding-partitions-to-aws-glue-using-node-lambda-only-a992c124973b?source=rss-246370aaad7e------2</link>
            <guid isPermaLink="false">https://medium.com/p/a992c124973b</guid>
            <category><![CDATA[glue]]></category>
            <category><![CDATA[kinesis-firehose]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[partitioning]]></category>
            <dc:creator><![CDATA[Tobin]]></dc:creator>
            <pubDate>Sat, 24 Aug 2019 10:39:15 GMT</pubDate>
            <atom:updated>2026-03-18T18:52:58.154Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*LQu6FiYBiwqaxr_K" /><figcaption>Photo by <a href="https://unsplash.com/de/@clark_fransa?utm_source=medium&amp;utm_medium=referral">Arnold Francisca</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Situation</h3><ol><li>An AWS Kinesis Firehose has been set up to feed into S3</li><li><em>Convert Record Format </em>is ON into parquet and mapping fields against a user-defined table in AWS Glue.</li><li>Write to S3 is using Hive or Firehose partitioning (or any custom partitioning key prefix)</li><li>Glue Table is partitioned along the same lines</li></ol><h3>Problem</h3><p>Feeding Kinesis Firehose records into S3 as parquet is fantastic for easy querying using Athena; with auto time-series partitions in Firehose the data can be very efficiently queried. As partitioned data volume is incremented with new S3 objects, partitions must be loaded into Athena / Glue before running queries (when not using partitions everything appears under the single table location).</p><h4>Crawler</h4><p>This can be achieved using a scheduled Crawler. Crawlers can get expensive: with a lot of data each crawl takes time, and wanting real-time data requires frequent crawling. Operating on a schedule therefore means trading TTL against cost.</p><h4>Lambda using S3 events</h4><p>This removes the scheduling issue by invoking the addition method whenever new objects are added. However it still relies on either scanning the S3 data and ADD missing partitions, or running MSCK REPAIRs. Both require running a query on Athena.</p><h3>How do the partitions work?</h3><p>Think of Glue Partitions as a map between a combination of known values and a specific directory. The SDK refers to Values as the array of values mapping to a specific Partition entry, which in turn explicitly states which directory in S3 to search / find objects.</p><h3>Solution</h3><ol><li>Take advantage of S3 events to only do anything when there is actually relevant new data</li><li>Use the event data object to work out where the data has been added</li><li>Use the aws-sdk::glue to query instead of Athena</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*bk1vUvhmo8DGmJvNUQ13IQ.png" /><figcaption>Representative Cloudformation template</figcaption></figure><p>Setup Firehose to deliver successfully processed records to a path e.g. processed/ and allow it to add the timepath automatically. In this case, it is not necessary to use the Hive formatting. This results in keys like:</p><pre>processed/2019/08/01/&lt;filename&gt;.parquet</pre><p>Personally, I add relevant source_records/ and error/ prefixes too.</p><p>Create a Lambda Notification subscription in the S3 bucket, filtering on the processed key prefix. Kinesis adds files to S3 via PUT so use the s3:ObjectCreated:Put event (note that the console uses ObjectCreated:Put).</p><pre>Bucket:<br>    Type: &#39;AWS::S3::Bucket&#39;<br>    Properties:<br>      NotificationConfiguration:<br>        LambdaConfigurations:<br>          - Event: &#39;s3:ObjectCreated:Put&#39;<br>            Function: !GetAtt <br>              - AutoAddPartitionFunction<br>              - Arn<br>            Filter:<br>              S3Key:<br>                Rules:<br>                  - Name: prefix<br>                    Value: processed</pre><h4>Lambda</h4><p>We should always get Records.length === 1 but just to be sure, loop the Records. The key of the new object can be parsed for some juicy partition Values data. Use glue.getPartition() to find out if this desired partition exists. Using await, if the partition does not exist a 400 EntityNotFoundException is conveniently thrown.</p><p>Creating a new partition using glue.createPartition() is quite complex as the StorageDescriptor must be fully populated with e.g. the column data.</p><p>Conveniently the StorageDescriptor returned from glue.getTable() is mostly identical; the Table location is at the parent level.</p><pre>glue.getTable() =&gt; StorageDescriptor.Location<br>=&gt; &#39;s3://&lt;bucket&gt;/processed/&#39;</pre><p>The new partition location can be determined by concatenating the Table Location with the object key.</p><p>For the DatabaseName and TableName environment variables are a good option, but unfortunately referencing them in Cloudformation creates a Circular Dependency :(</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae8518e977597d703cecb4789d36595c/href">https://medium.com/media/ae8518e977597d703cecb4789d36595c/href</a></iframe><h3>Conclusion</h3><p>An awesome tool, the only real sticking points I had with Athena was dealing with partitions on time-incrementing data sources. The provided Crawler solution is perhaps more ‘integrated’ however feels a bit clumsy and costs are relatively high. As this lambda only runs intermittently it often requires cold starting and therefore each run can be a bit lengthy (&lt;800ms, $$), but overall it appears to be cheaper and faster than the other methods.</p><p>We use this on <a href="https://proofenance.com/">Proofenance</a> to study our audit logs quickly and easily.</p><h4>Further Reading</h4><ul><li><a href="https://gethelios.dev/blog/5-microservices-challenges-and-blindspots-for-developers/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">5 Microservices Challenges and Blindspots for Developers</a></li><li><a href="https://gethelios.dev/blog/cut-engineering-costs-save-time-helios/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Microservices Monitoring: Cutting Engineering Costs and Saving Time</a></li><li><a href="https://gethelios.dev/blog/testing-microservices-with-helios/?utm_source=medium&amp;utm_medium=content&amp;utm_campaign=cloudnativedaily">Testing Microservices - Trace Based Integration Testing Example</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a992c124973b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/cloud-native-daily/automatically-adding-partitions-to-aws-glue-using-node-lambda-only-a992c124973b">Automatically Add Partitions to AWS Glue using Node/Lambda Only</a> was originally published in <a href="https://medium.com/cloud-native-daily">Cloud Native Daily</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>