<?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 Jorge Rodriguez on Medium]]></title>
        <description><![CDATA[Stories by Jorge Rodriguez on Medium]]></description>
        <link>https://medium.com/@j4rs?source=rss-fdd71b0b7083------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*XR5GoWWJruzXP39vYyovbA.png</url>
            <title>Stories by Jorge Rodriguez on Medium</title>
            <link>https://medium.com/@j4rs?source=rss-fdd71b0b7083------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 14:03:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@j4rs/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[Protect your servers with Rack Attack.]]></title>
            <link>https://medium.com/get-on-board-dev/protect-your-servers-with-rack-attack-9bbedceb5929?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/9bbedceb5929</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rack-attack]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 17:14:09 GMT</pubDate>
            <atom:updated>2023-06-29T18:45:05.853Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*xlYGa4NvsbL2OMwW" /><figcaption>Photo by <a href="https://unsplash.com/@wizwow?utm_source=medium&amp;utm_medium=referral">Donald Giannatti</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Your <em>Rails</em> application will be attacked, that is a fact, either today or in the future, it doesn’t matter whether your site is or not popular, attackers do it for money, for ego, or for fun.</p><p><a href="https://github.com/rack/rack-attack">Rack attack</a> gem is a gem (pun intended) when it is about stopping attackers or adding limits to the rate of requests to your <em>Rails</em> application.</p><p>We have been iterating over setting up the gem to protect our servers not only from malicious people but also from abusive (in a good sense) users that hit our endpoints too frequently.</p><p>The final result is this small script that hopefully can serve you too. Here is a summary of what it does although the comments are self-explanatory:</p><ul><li>Always allow requests from localhost</li><li>Use <em>Redis</em> as the data store to keep a register of requests increments per IP</li><li>Keep a <em>Redis — </em>could be a memory<em> — </em>register of known malicious IPs (from previous attacks) and block them all</li><li>Fool the attackers by responding with <em>HTTP</em> status of <strong>503</strong> which will make them believe they succeeded in shutting down your site 😅</li><li>Limit the amount — stored in <em>ENV</em> vars — of requests (GET and POST) your users can make to certain parts of your applications like your API in a certain amount of time (period in secs).</li><li>Track <em>attack patterns</em> and be notified about them. In our case, the script enqueues a job in <em>Sidekiq</em> that sends alerts to the team to verify the IPs registering — as attackers — and blocking them.</li></ul><pre># config/initializers/rack_attack.rb<br><br># Allow localhost<br>Rack::Attack.safelist_ip(&quot;127.0.0.1&quot;)<br><br># Use Redis as DS<br>Rack::Attack.cache.store = ActiveSupport::Cache::RedisCacheStore.new<br><br># List of known attackers<br># Support ips in the format IP a.b.c.d or with subnet a.b.c.d/f<br># Ref: https://github.com/rack/rack-attack#blocklist_ipip_subnet_string<br>KNOWN_ATTACKERS_IP_KEY = &quot;enter-your-id-here&quot;<br># Block them all<br>Redis<br>  .new<br>  .smembers(KNOWN_ATTACKERS_IP_KEY)<br>  .each { |ip| Rack::Attack.blocklist_ip(ip) }<br><br># Fool the attackers<br>Rack::Attack.blocklisted_responder = lambda do |request|<br>  # Using 503 because it may make attacker think that they have successfully<br>  # DOSed the site. Rack::Attack returns 403 for blocklists by default<br>  [503, {}, [&quot;Service Unavailable&quot;]]<br>end<br><br># Throttles<br>API_PATH = /\/api\//<br>Rack::Attack<br>  .throttle(&quot;API_POST&quot;,<br>            limit: ENV.fetch(&quot;YOUR_API_POST_LIMIT&quot;, 10).to_i,<br>            period: 5) do |req|<br>    req.ip if req.path.match?(API_PATH) &amp;&amp; req.post?<br>  end<br><br>Rack::Attack<br>  .throttle(&quot;API_GET&quot;,<br>            limit: ENV.fetch(&quot;YOUR_API_GET_LIMIT&quot;, 100).to_i,<br>            period: 5) do |req|<br>    req.ip if req.path.match?(API_PATH) &amp;&amp; req.get?<br>  end<br><br>#<br># Set up a track to catch potential attackers<br>#<br>ATTACK_PATTERN = &quot;ATTACK_PATTERN&quot;<br>Rack::Attack<br>  .track(ATTACK_PATTERN,<br>         limit: ENV.fetch(&quot;YOUR_AP_REQUESTS_LIMIT&quot;, 600).to_i,<br>         period: 60) do |req|<br><br>    req.ip unless req.path.match?(API_PATH) # Already throttled<br>  end<br><br># Get notified<br>ActiveSupport::Notifications<br>  .subscribe(&quot;track.rack_attack&quot;) do |name, start, finish, request_id, payload|<br>    request = payload[:request]<br>    remote_ip = request.ip<br><br>    throttle_data = request.env[&quot;rack.attack.throttle_data&quot;]<br>    throttle_name = throttle_data.first[0]<br><br>    # Only notify if this is an attack pattern<br>    if throttle_name == ATTACK_PATTERN<br>      # Capture insight data<br>      data = throttle_data[throttle_name]<br>      %i[<br>        content_type forwarded_for fullpath request_method media_type path query_string<br>        referer url user_agent xhr?<br>      ]<br>      .each { |method| data[method] = request.send(method) rescue nil }<br>      # Enqueue the notification<br>      RackAttackNotificationWorker.perform_async(remote_ip, data.stringify_keys)<br>    end<br>  end</pre><p>Even if you need no rate limits — just remove the <em>throttle</em> part of the script — it is still useful to protect your site by blocking malicious IPs while whitelisting the good ones.</p><p>Once you start collecting the attacker&#39;s IP, just add it to the <em>Redis</em> entry and restart your application.</p><pre>&gt; Redis.new.sadd?(KNOWN_ATTACKERS_IP_KEY, &quot;37.212.0.0/19&quot;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9bbedceb5929" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/protect-your-servers-with-rack-attack-9bbedceb5929">Protect your servers with Rack Attack.</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails 7 breaks old signed messages]]></title>
            <link>https://medium.com/get-on-board-dev/rails-7-breaks-old-signed-messages-f914d7576d75?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/f914d7576d75</guid>
            <category><![CDATA[rails-7]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[action-text]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Wed, 28 Jun 2023 01:17:31 GMT</pubDate>
            <atom:updated>2023-06-29T18:51:00.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RhkAVzjxdE59W9kB" /><figcaption>Photo by <a href="https://unsplash.com/@towfiqu999999?utm_source=medium&amp;utm_medium=referral">Towfiqu barbhuiya</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you find yourself migrating to rails 7.x and using its defaults, it is very likely your persisted signed messages (used mostly in URLs) will stop working.</p><p>Signed messages come from using <strong>ActiveSupport::MessageVerifier</strong> for scenarios like remember-me tokens or auto-unsubscribe links where there is no session available.</p><p><em>ActionText</em> or <a href="https://trix-editor.org/"><em>Trix</em> editor</a> use it too to create permanent signed links to the uploaded attachments (through <strong>ActiveStorage</strong>).</p><pre># config/application.rb<br># <br>module Getonboard<br>  class Application &lt; Rails::Application<br>    # Use the default settings of Rails 7<br>    config.load_defaults 7.0<br>    ...<br>  end<br>end</pre><p>Our case wasn’t different, we use <em>Trix</em> editor and a lot of remember-me tokens or subscribe/unsubscribe links across our codebase, also secrets encrypted to allow our users to access their private data thru using <a href="https://api-doc.getonbrd.com/">our API</a>.</p><p>The problem is not well documented, and we had to dig deeper to diagnose it and come up with a solution. The issue had to do with <a href="https://guides.rubyonrails.org/upgrading_ruby_on_rails.html#key-generator-digest-class-changing-to-use-sha256">Rails 7 changing the key generation for signing messages from using SHA1 to using SHA256</a>, so your old permanent signatures were encrypted with <em>SHA1</em> and now Rails is trying to decrypt them by using a <em>SHA256</em> digest generated key.</p><p>The good news is that buried in the <strong>ActiveSupport::MessageVerifier </strong>API documentation is the support to add rotations keys as fallbacks in case the message verifier fails using the original — claps to the developers for the clever decision to do that.</p><p><strong>Our solution consisted in adding rotation keys for all the message verifiers used across the codebase</strong> — you can accommodate this code for your personal case too.</p><pre># config/initializers/message_verifiers_rotates.rb<br>#<br>Rails<br>  .application<br>  .config<br>  .after_initialize do |app|<br>    # Create an old SHA1 key generator<br>    sha1_key_generator =<br>      ActiveSupport::KeyGenerator.new(app.secret_key_base,<br>                                      iterations: 1000,<br>                                      hash_digest_class: OpenSSL::Digest::SHA1)<br><br>    # Create rotates for all the currently used veririfier<br>    # In theory all the verifiers but ActiveStorage can be<br>    # removed from the list in a few months from now on.<br><br>    # Note: ActiveStorage is used by trix to create permanent signed ids<br>    # for the attached images of the blog posts.<br>    # <br>    verifiers = [<br>      &quot;ActiveStorage&quot;,<br>       ...<br>    ]<br><br>    verifiers.each do |verifier|<br>      app<br>        .message_verifier(verifier)<br>        .rotate(sha1_key_generator.generate_key(verifier))<br>    end<br>  end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f914d7576d75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/rails-7-breaks-old-signed-messages-f914d7576d75">Rails 7 breaks old signed messages</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deshabilitar *react-hooks/exhaustive-deps* es tóxico.]]></title>
            <link>https://medium.com/get-on-board-dev/deshabilitar-react-hooks-exhaustive-deps-es-t%C3%B3xico-d35feda7eb04?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/d35feda7eb04</guid>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Fri, 27 Mar 2020 22:08:05 GMT</pubDate>
            <atom:updated>2020-03-30T13:01:40.663Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mejor revisa tu implementación.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*bPKoLZdXOft_vX2L" /><figcaption><a href="https://unsplash.com/photos/m_l-ioF8-q4">Unsplash</a></figcaption></figure><p>El team de <em>React</em> escribió <a href="https://www.npmjs.com/package/eslint-plugin-react-hooks">este plugin de ESLint</a> para hacer cumplir <a href="https://reactjs.org/docs/hooks-rules.html">las reglas</a> a la hora de escribir funciones tipo hooks. Entre la lista de reglas está la del chequeo de dependencias — exhaustive-deps — que lanza errores cuando detecta que la función invocada en el hook, depende de una propiedad o estado que debe ser recordado, o incluso pueda quedar obsoleto en el próximo re-pintado de la componente:</p><pre>React Hook useEffect has a missing dependency: ‘sayHi’. Either include it or remove the dependency array.eslint(react-hooks/exhaustive-deps)</pre><p>Es difícil mantener este control en la mente mientras escribimos el código, y es parte de la gracia de usar el plugin react-hooks.</p><p>Hay ocasiones donde siguiendo lo documentado por <em>React</em> queremos que <a href="https://medium.com/get-on-board-dev/react-hooks-optimizando-useeffect-o-effect-hook-49fbe4fc2c18">nuestra función hook se ejecute solo una vez</a>, cuando se monta la componente, como en el siguiente código:</p><pre>const Greeting = ({name}) =&gt; {</pre><pre>  const sayHi = () =&gt; {<br>    console.log(&#39;Hi there&#39;, name);<br>  };</pre><pre>  useEffect(() =&gt; {<br>    sayHi();<br>    <em>// eslint-disable-next-line react-hooks/exhaustive-deps<br></em>  }, []); // arreglo vacío - say Hi solo cuando se monta Greeting<br>};</pre><p>Y frustra encontrarse con el error de que Greeting tiene una dependencia no declarada. Dado que en teoría no estamos haciendo nada errado la solución suele ser culpar al plugin de ser excesivamente estricto y deshabilitarlo.</p><p>Lo que explica que la función sayHi solo va a ejecutarse una vez es que el arreglo de dependencias vacío le indica a <em>React</em> qué esta función no depende de nada relacionado al estado de la componente, por ende no necesita ser ejecutada nuevamente la próxima vez, nada va a cambiar.</p><p>Pero de mirar el código, el resultado de la ejecución de sayHi sí depende de la propiedad name, e incluirla en las dependencias no va cambiar el comportamiento esperado — de ejecutarse solo una vez — a no ser que en el tiempo de vida de la componente “algo” le asigne un valor diferente a name, o sea la componente necesita reaccionar y re-pintarse porque su estado interno cambió.</p><p>Si el comportamiento deseado fuera ejecutar sayHi <strong>solo una vez a pesar que el valor de la propiedad cambia</strong>, <em>React</em> <a href="https://reactjs.org/docs/hooks-faq.html#what-can-i-do-if-my-effect-dependencies-change-too-often">documenta acá</a> un recurso para hacerlo usando el hook useRef para guardar el valor, en este caso:</p><pre>const Greeting = ({name}) =&gt; {</pre><pre>  const fixedName = useRef();</pre><pre>  const sayHi = () =&gt; {<br>    console.log(&#39;Hi there&#39;, fixedName.current);<br>  };</pre><pre>  useEffect(() =&gt; {<br>    fixedName.current = name<br>  }); // guarda el valor de name en fixedName yse ejecuta primero.</pre><pre>  useEffect(() =&gt; {<br>    sayHi();<em><br></em>  }, []); // no más error y el effect solo corre una vez.<br>};</pre><p>Esta implementación no es ideal, es un recurso. El efecto que guarda el valor de name en fixName.current se ejecuta cada vez que la componente se re-pinta pero el efecto que ejecuta sayHi se ejecuta solo la primera vez., Esto funciona porque además <em>React</em> ejecuta los hooks <strong>en el orden en que los encuentra</strong> en el código.</p><blockquote>Deshabilitar la regla es tóxico porque en codebases grandes es difícil mantener el control de cuándo o cuándo no se deben ejecutar los hooks basado en los cambios de estado de las componentes. La regla expone y ayuda a mantener las dependencias documentando el hook, es fácil mirando en el arreglo entender en qué momentos el code va a ser ejecutado.</blockquote><p>Usar un recurso es mejor que deshabilitar la regla porque significa que <strong>entiendes el trasfondo de tu implementación</strong> y por ende <strong>futuros comportamientos inesperados/no-deseados</strong>, si fuera el caso.</p><p><em>Como siempre, si tienes comentarios déjanos un comentario o escríbenos directamente a team at getonbrd.com</em> 🤗.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d35feda7eb04" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/deshabilitar-react-hooks-exhaustive-deps-es-t%C3%B3xico-d35feda7eb04">Deshabilitar *react-hooks/exhaustive-deps* es tóxico.</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review apps en Heroku, parte 3: Scripts personalizados.]]></title>
            <link>https://medium.com/get-on-board-dev/review-apps-en-heroku-parte-3-scripts-personalizados-5ac3466c38a2?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ac3466c38a2</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[progressive-delivery]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Thu, 12 Mar 2020 13:08:09 GMT</pubDate>
            <atom:updated>2020-03-12T23:54:28.477Z</atom:updated>
            <content:encoded><![CDATA[<h3>Review apps en Heroku: Scripts personalizados – parte 3</h3><h4>Como alimentar la base de datos o crear dominios personalizados automáticamente cuando se crea la aplicación.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*clWCng6diUXjROZl" /><figcaption><a href="https://unsplash.com/photos/XJXWbfSo2f0">Unsplash</a></figcaption></figure><p>En la <a href="https://medium.com/get-on-board-dev/review-apps-c%C3%B3mo-se-configuran-parte-2-68388356de52">segunda parte de esta serie</a> mostramos cómo configuramos una review app en <a href="https://www.getonbrd.com/">Get on Board</a>.</p><pre># Ejecuta tareas tipo rake al crear y destruir la review app<br>“scripts”: {<br> “postdeploy”: “rails getonbrd:heroku:review_app_setup getonbrd:db:create_sample_data”,<br> “pr-predestroy”: “rails getonbrd:heroku:review_app_predestroy”<br>}</pre><p>Lo que queda es revisar en detalle cómo es posible personalizar una aplicación con código que se ejecuta una vez que esta es creada — postdeploy — o después de ser destruida — pr-predestroy.</p><h4>Data seeds</h4><p>Es conveniente alimentar una review app con un set mínimo de datos de pruebas. <em>Rails</em> provee <a href="https://edgeguides.rubyonrails.org/active_record_migrations.html#migrations-and-seed-data">db:seeds</a>, sin embargo, cuando tienes mucha data organizada en múltiples modelos dependientes entre sí, se hace incómodo tenerlo todo en un mismo archivo.</p><pre><em># companies.yml<br></em>DEFAULTS: &amp;DEFAULTS<br>  name: $LABEL<br>  email: dev+company_$LABEL@getonbrd.com<br>  web: https://www.$LABEL.com</pre><pre>getonbrd:<br>  &lt;&lt;: *DEFAULTS<br>  name: Get on Board<br>  description: Awesome jobs for awesome people.<br>  country: CL</pre><pre>...</pre><p>A nosotros se nos ocurrió hacer uso de <a href="https://api.rubyonrails.org/v6.0.2.1/classes/ActiveRecord/FixtureSet.html">otro mecanismo</a> del framework, que usualmente se usa para alimentar el ambiente de <em>testing</em> con datos de muestra. Entre las ventajas de usar <strong>fixtures</strong> está la de declarar la data en archivos <strong>YAML</strong> ☝️, formato amigable que resulta conveniente cuando — como es nuestro caso — colaboradores que no necesariamente entienden código pueden agregar nuevos registros.</p><p>Para cargar la muestra en la review app creamos una tarea que importa los <em>fixtures y </em>ejecuta un par de métodos de clean-up y sanity check de la data:</p><pre># rake file<br>task create_sample_data: :environment do<br> CreateSampleData.run(false)<br>end</pre><pre># CreateSampleData.rb<br>class CreateSampleData<br>  def self.run(perform_reset_db =false)<br>    new.run(perform_reset_db)<br>  end</pre><pre>  def run(perform_reset_db = false)<br>    reset_db if perform_reset_db<br>    without_contraints { load_fixtures }<br>    fill_long_texts<br>    update_tenant_hostnames<br>    ...<br>    sanity_check<br>  end<br>  <br>  ...<br>  <br>  def without_contraints<br>    drop_constraints<br>    yield<br>  ensure<br>    create_constraints<br>  end</pre><pre>  def load_fixtures<br>    perform &#39;Loading fixtures&#39; do<br>      Rake::Task[&#39;db:fixtures:load&#39;].invoke<br>    end<br>  end<br>  <br>  ...</pre><pre>end</pre><blockquote>Protip: No es posible cargar fixtures en una base de datos diferente a testing porque se violan constraints tales como primaries o secondaries keys. Por eso ejecutamos la carga dentro de un bloque que, usando funcionalidades nativas de PostgreSQL, eliminan los constraints — drop_constraints — por un rato, recreándolos — create_constraints— una vez que la data es cargada.</blockquote><h4>Dominios personalizados</h4><p><em>Heroku</em> provee un dominio en la forma [nombre-de-la-app].herokuapp.com cuando una aplicación es creada y no todas necesitan cambiarlo para funcionar. Get on Board, por su naturaleza multi-tenant necesita configurar dominios personalizados para los países donde está presente. La forma de hacer esto es crear registros <strong>CNAME</strong> en un <strong>DNS</strong> externo que apunten a la review app. Heroku documenta bien el <a href="https://devcenter.heroku.com/articles/custom-domains">proceso manual</a>.</p><p><a href="https://dnsimple.com/">DNSimple</a> es un proveedor de dominios que provee una API — y una <a href="https://github.com/dnsimple/dnsimple-ruby">gema</a> ruby — con la que puedes interactuar para modificar las tablas DNS de tus dominios por cinco dólares al mes.</p><p><a href="https://devcenter.heroku.com/articles/platform-api-reference">Platform API</a> — y su <a href="https://github.com/heroku/platform-api">gema</a> en ruby — es la forma de interactuar con <em>Heroku</em> desde el código de tu aplicación.</p><p>Uniendo a ambos es posible crear dominios personalizados una vez que la aplicación ya existe:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/516f23d1343f93b8256c4e571daa3638/href">https://medium.com/media/516f23d1343f93b8256c4e571daa3638/href</a></iframe><p>Finalmente, una vez que se aprueban los cambios introducidos en la review app y el nuevo code se va a <em>staging</em> o <em>producción,</em> la app es destruida. En este punto podemos ejecutar un script para que haga housekeeping, como borrar las entradas <strong>CNAME</strong> creadas anteriormente en <em>DNSimple</em>:</p><pre>task :review_app_predestroy do<br>  require “dnsimple”<br>  heroku_app_name = ENV[“HEROKU_APP_NAME”]<br>  <br>  <em># Wipe the DNS records<br>  </em>dnsimple_account_id = ENV[“DNSIMPLE_DEV_ACCOUNT_ID”]<br>  </pre><pre>  dnsimple_client = Dnsimple::Client.new(<br>    access_token: ENV[‘DNSIMPLE_ACCESS_TOKEN’]<br>  )</pre><pre>  resp = dnsimple_client.zones.zone_records(<br>    dnsimple_account_id,<br>    GOB_DEV_DOMAIN,<br>    { filter: { name_like: “#{heroku_app_name}” } }<br>  )</pre><pre>  resp.data.each do |zone|<br>    dnsimple_client.zones.delete_zone_record(<br>      dnsimple_account_id,<br>      GOB_DEV_DOMAIN,<br>      zone.id<br>    )<br>  end<br>end</pre><p><em>Como siempre, si te surgieron dudas o quieres compartir tips relacionados con este post puedes dejarnos un comentario o escribirnos directamente a team at getonbrd.com </em>🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ac3466c38a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/review-apps-en-heroku-parte-3-scripts-personalizados-5ac3466c38a2">Review apps en Heroku, parte 3: Scripts personalizados.</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Our New Payment Subsystem]]></title>
            <link>https://medium.com/get-on-board-dev/our-new-payment-subsystem-c7964be86650?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7964be86650</guid>
            <category><![CDATA[payment-processing]]></category>
            <category><![CDATA[3d-secure]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[payment-integration]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Sat, 08 Feb 2020 00:14:26 GMT</pubDate>
            <atom:updated>2020-02-08T00:14:26.976Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing a reusable payment subsystem that supports the upcoming <a href="https://en.wikipedia.org/wiki/3-D_Secure">3D Secure protocol</a>.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*eN0x79Zx-L_h-ZmZ" /><figcaption><a href="https://unsplash.com/photos/Q59HmzK38eQ">Unsplash</a></figcaption></figure><p>We have been using <em>Stripe</em> to charge our customers since 2014. How we integrated it back then wasn’t the most important stuff to care about, as we didn’t know whether we were onto something with our product. What was important in those days — and still is — was to be able to pivot quickly from one revenue model to another validating our hypotheses. It continues to be that way but today we are not under the radar anymore.</p><p>Among the things we discovered was that we could charge for multiple pay-as-you-go features like <em>unlocking an individual hiring process</em>, or <em>packages of unlocks</em>, or <em>boost a job</em>. Since integrating payments wasn’t meant to be reusable, each new paid feature had its own flow and code copied and pasted from another one already implemented.</p><p>Being honest, it wasn’t that bad, as it was easy to copy-and-paste code customizing the amount to be charged and some other logic. However, at this point, we had acquired a <em>technical debt</em> dealing with at least three payment controllers and views that were the same thing with subtle differences. All because of the trade-off of delivering fast measuring whether our customers were willing to pay for the new feature, deleting the code otherwise.</p><h4>Paying the debt</h4><p>By December 2019, we started to add a couple of new and not yet released features — one of which is <em>automated subscriptions</em>, the other still to be revealed — that needed payment with an uncommon characteristic, where customers will have to authorize the charges that the system will capture later on when they are offline (not present). This new capability means having the ability to store — with upfront authorization — the payment method to be charged in the future.</p><p>This time we felt motivated to do it the right way by taking time to design and rewrite everything from scratch. There were more reasons for doing it:</p><ul><li><strong>Migrate to the new </strong><a href="https://stripe.com/docs/payments/payment-intents"><strong>Payment Intents API</strong></a> — so far we were relying on the old <a href="https://stripe.com/docs/payments/accept-a-payment-charges">Charge API</a> — meaning support for the upcoming <a href="https://stripe.com/guides/strong-customer-authentication">Strong Customer Authentication</a> European regulation to be fully enforced by December 31, 2020.</li><li><strong>One code for managing the process</strong>: Payment is almost always the same: users select what service they want to pay for, enter or select a payment method and authorize the charge. There are custom parameters and custom business logic for each flow but they can ultimately be handled in one place and with one code.</li><li><strong>Same UX and UI</strong>: As the flow is pretty similar on each payment, it is better to present the users with the same — and to some extent familiar — experience everywhere and every time they will pay for a feature.</li></ul><h4>Implementation</h4><p>The first decision was not to rely on <a href="https://stripe.com/payments/checkout">Stripe Checkout</a>, even when it seemed the obvious way to go, as there was little to implement at our side. However, the downsides start to pile up when you want to have control of the user experience because using checkout means the experience is hosted-in and controlled-by Stripe, so we decided to take the long path and implement — as a tech company — everything on our own.</p><p>At the backend, we divided managing the payments in three modules or sets of endpoints, each with specific functions:</p><ul><li><em>Payment methods controller</em>: Handling the <strong>attaching</strong>, <strong>detaching</strong> or <strong>setting as default </strong>a payment method (i.e: credit card).</li><li><em>Intents controller</em>: Handling the <strong>verification</strong> of a new payment method and/or the <strong>authorization</strong> of a charge.</li><li><em>Payments callback controller</em>: Handling all the tasks that happen on the background once the payment is collected — or fails — , for instance <strong>notifying</strong> customers by email and <strong>executing</strong> the business logic related to the service the users paid for, for instance, increasing the unlocks quota after buying a <em>package of unlocks</em> or running the matching algorithm after <em>boosting a job.</em></li></ul><p>Then at the frontend, we created a UI component in <em>React</em> for managing — adding, deleting or setting as default — payment methods.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XEvnnlIIlMnhPeH634d9Dg.png" /></figure><p>And a UI component for authorizing the payment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f7hy62raBbgcOms4-I38kQ.png" /></figure><p>The user is presented with the same interface across the site.</p><h4>Considerations</h4><p>I won’t dig into the specifics but will list instead some of the issues we considered while designing and implementing the subsystem:</p><ul><li>The UI components were thought to be shared and so fully customized — through properties — even at the level of using them as <em>modal</em> or <em>inline</em></li><li>There is heavy communication with the <em>Stripe</em> API at the backend (<em>ruby</em>) and frontend (<em>Javascript</em>) on each user interaction.</li><li>SetupIntent and PaymentIntent are concepts or models at <em>Stripe</em> mapped within our codebase too, so we keep a copy (reference) at our side in order to own the checkout flow experience and reduce the network communication with <em>Stripe.</em></li><li>Never attempt to handle what happens next to a successful charge at the frontend (browser), because it is possible for customers to leave the page after the payment is complete but before the post-charge process initiates. The best practice hence is to monitor — by listening to <a href="https://stripe.com/docs/webhooks">webhooks events</a> that <em>Stripe</em> sends to the application using a direct and secure channel — the <em>status of a charge</em>, executing the subsequent business logic related to the feature the customer is paying for.</li><li>Keep the customers aware of everything that is happening with their payments by notifying them, for instance, when a payment succeeds or fails (with the cause and action to take next) or a new credit card is added or deleted.</li><li>Track the failed attempts and notify the dev and sales teams with context info to offer help proactively to the customer 😉.</li></ul><p>Handling payments is not easy — even when <em>Stripe</em> facilitates a lot — especially having to deal with the new transactional state of a charge via the new <a href="https://stripe.com/docs/payments/payment-intents">payment intents</a> and <a href="https://stripe.com/docs/payments/setup-intents">setup intents</a> support. Hopefully, this post gave you some insight into some of the things to bare in mind and take care of when going with your implementation.</p><p><em>I am pretty sure you have questions and we are more than happy to answer them, so leave us a comment or drop us a line to team at getonbrd dot com </em>🤓.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7964be86650" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/our-new-payment-subsystem-c7964be86650">Our New Payment Subsystem</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Review apps en Heroku: ¿Cómo se configuran? — parte 2]]></title>
            <link>https://medium.com/get-on-board-dev/review-apps-c%C3%B3mo-se-configuran-parte-2-68388356de52?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/68388356de52</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[progressive-delivery]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[devops]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Fri, 20 Dec 2019 13:12:55 GMT</pubDate>
            <atom:updated>2019-12-20T20:51:51.877Z</atom:updated>
            <content:encoded><![CDATA[<h3>Review apps en Heroku: ¿Cómo se configuran? — parte 2</h3><h4>Tips en detalle de lo importante (y lo no tan conocido)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ag5CFmKbMyccicL-" /><figcaption><a href="https://unsplash.com/photos/Lks7vei-eAg">Unsplash</a></figcaption></figure><p><a href="https://medium.com/get-on-board-dev/review-apps-cada-pull-request-es-una-nueva-app-parte-1-b459c16d8e43">En la primera parte</a> de la serie explicamos qué son, así como los beneficios de implementar review apps como parte del pipeline de desarrollo y despliegue de tu aplicación en Heroku. En este post damos tips de cómo configurar ciertas partes de una review app no tan bien documentadas y mostramos ejemplo de cómo lo hicimos nosotros.</p><h4>Un archivo de configuración</h4><p>Las review apps son creadas manual o automáticamente cuando un pull request es creado en GitHub. Heroku usa <a href="https://devcenter.heroku.com/articles/app-json-schema">el archivo <strong><em>app.json</em></strong></a> en la raíz del proyecto para configurarla(s).</p><p>Todo el setup que necesita la aplicación es especificado en este archivo, por mencionar algunos: los <a href="https://devcenter.heroku.com/articles/add-ons">add-ons</a> y sus planes (qué base de datos, o servidor de cache necesita y el precio), <a href="https://devcenter.heroku.com/articles/buildpacks">los buildpacks</a> (soporte que necesita la app para ser ejecutada, por ejemplo la JVM de Java o cierta versión de NodeJS o Ruby), las variables de ambiente, <a href="https://www.heroku.com/dynos">el hardware</a> (cantidad de dynos web y/o worker así como el tamaño de cada uno), <a href="https://devcenter.heroku.com/articles/stack">el stack</a> (versiones de linux y librerías, esto es importante si se estás probando una migración a un stack diferente), o los scripts (ejecutados luego de creada, o antes de ser destruída la app — más sobre esto luego).</p><p>Cómo crear y configurar una review app está bien documentado/actualizado <a href="https://devcenter.heroku.com/articles/github-integration-review-apps">acá</a> y <a href="https://devcenter.heroku.com/articles/app-json-schema">acá</a>, por lo que en el post solo daremos tips — que no encuentras en la doc — y cómo en Get on Board implementamos ciertas particularidades de nuestra aplicación, tales como alimentar la base de datos o cambiar el DNS para soportar dominios personalizados.</p><h4>Variables de entorno inyectadas</h4><p>Hay tres variables de entorno que Heroku inyecta a toda review app y que pueden ser útiles en el momento de querer personalizar tu aplicación:</p><ul><li><strong>HEROKU_APP_NAME</strong>: El nombre de la review app que Heroku genera en forma random para evitar colisión. Una vez creada el nombre no cambia más</li><li><strong>HEROKU_BRANCH</strong>: El nombre del branch remoto en al cual está basado el pull request</li><li><strong>HEROKU_PR_NUMBER</strong> : El número del pull request en GitHub</li></ul><h4>Ambiente de Rails</h4><p>Heroku usa la misma convención que Rails para saber sobre qué ambiente ejecutar la aplicación mirando dentro de la variable RAILS_ENV.</p><p>Cuál valor escoger entre <em>staging</em> o <em>producción</em> es normalmente basado en qué se quiere validar en una review app, pero lo más común es que estén basadas en staging. En nuestro caso el pipeline está formado por <em>development</em> → <em>review apps</em> → <em>staging</em> → <em>production</em>, y las RA están basadas en el ambiente de staging que hace parity con producción, de esa forma tenemos una <a href="https://12factor.net/dev-prod-parity">aproximación a producción</a> donde es posible jugar y equivocarse.</p><h4>Scripts</h4><p>Hay dos comandos opcionales que son ejecutados en el ciclo de vida de una review app y que puedes personalizar:</p><ul><li>postdeploy: Se ejecuta <strong>una sola vez</strong> cuando la RA es creada y después que se ejecuta <a href="https://devcenter.heroku.com/articles/release-phase">la fase de release</a>. <strong>No es ejecutado</strong> en cambios subsecuentes en el pull request como nuevos commits. Es usando este script donde por ejemplo insertas datos de prueba o configuras el DNS, más sobre esto luego</li><li>pr-predestroy: Se ejecuta antes de que se destruye la RA — de forma manual o porque se hace merge del pull request — y sirve para hacer un cleanup de cualquier configuración que hayas hecho en el comandopostdeploy</li></ul><blockquote>Tip: Si necesitas ejecutar código cada vez que haya una actualización del pull request y por ende de la review app usa <a href="https://devcenter.heroku.com/articles/release-phase">la fase de release</a>, que no es más que una entrada en el archivo Procfile. Por ejemplo release: rails db:migrate va a asegurarse de siempre verificar y ejecutar las migraciones pendientes en la base de datos.</blockquote><h4>Ejemplos de nuestra configuración</h4><p>Sigue un fragmento de nuestro <strong><em>app.json</em></strong> con comentarios que puedes usar como guía mientras estudias la documentación en Heroku:</p><pre># Nuestra infraestructura consta de 1 dyno web y 1 dyno worker<br>“formation”: [<br>  { “process”: “web”, “quantity”: 1 },<br>  { “process”: “worker”, “quantity”: 1 }<br>],<br># Usamos bases de datos postgresql y redis,<br># y un servidor de memcache - (todos gratis en la RA ;)<br>&quot;addons&quot;: [<br>  &quot;heroku-postgresql:hobby-basic&quot;,<br>  &quot;memcachier:dev&quot;,<br>  &quot;heroku-redis:hobby-dev&quot;<br>],<br># Las variables de ambiente. Es recomendable que las secrets<br># como api or access tokens sean inicializadas directamente al<br># configurar las review apps, <a href="https://devcenter.heroku.com/articles/github-integration-review-apps#getting-started">acá la doc en Heroku</a>.<br>&quot;env&quot;: {<br>  &quot;HEROKU_API_TOKEN&quot;: &quot;&lt;access-token-here&gt;&quot;,<br>  &quot;DNSIMPLE_ACCESS_TOKEN&quot;: &quot;&lt;access-token-here&gt;&quot;,<br>  &quot;DNSIMPLE_DEV_ACCOUNT_ID&quot;: &quot;&lt;account-id&gt;&quot;,<br>  &quot;RAILS_ENV&quot;: &quot;staging&quot;<br>  ...<br>},<br># Ejecuta tareas tipo rake al crear y destruir la review app<br>&quot;scripts&quot;: {<br>  &quot;postdeploy&quot;: &quot;rails getonbrd:heroku:review_app_setup getonbrd:db:create_sample_data&quot;,<br>  &quot;pr-predestroy&quot;: &quot;rails getonbrd:heroku:review_app_predestroy&quot;<br>}</pre><h4>Scripts</h4><p>Nota como en el script postdeploy ejecutamos una tarea que alimenta la base de datos create_sample_data y antes review_app_setup. En está última configuramos un DNS externo (creando entradas CNAME) y luego creamos varios dominios personalizados para la review app.</p><p>Luego en el script pr-predestroy ejecutamos la tareareview_app_predestroy que limpia la misma tabla DNS (borrando las entradas CNAME) antes de que se destruya la aplicación y por ende los dominios personalizados.</p><p>Un par de notas respecto a los scripts:</p><ul><li>(a) Para crear los datos de prueba aprovechamos el mecanismo <a href="https://guides.rubyonrails.org/testing.html#the-low-down-on-fixtures">fixtures de rails</a>, conveniente por la forma en que se declaran y organizan los datos usando archivos <em>yaml</em></li><li>(b) Luego para crear los dominios personalizados usamos una cuenta en <a href="https://dnsimple.com/">DNSimple</a> que brinda una API para jugar con la configuración de los DNS. Además usamos la <a href="https://github.com/heroku/platform-api">API de Heroku</a> para crear los dominios en la review app</li></ul><p>Síguenos si quieres enterarte de cómo hicimos (a) y (b) que explicaremos en más detalles en próximos posts de la serie.</p><p><em>Como siempre si quiere compartir tus tips o tienes dudas o preguntas relacionadas con este post puedes dejarnos un comentario o escribirnos directamente a team at getonbrd.com </em>🤗</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68388356de52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/review-apps-c%C3%B3mo-se-configuran-parte-2-68388356de52">Review apps en Heroku: ¿Cómo se configuran? — parte 2</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[No me gustan las one on one (1:1)]]></title>
            <link>https://medium.com/@j4rs/no-me-gustan-las-one-on-one-1-1-2cf693fde8b2?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf693fde8b2</guid>
            <category><![CDATA[one-on-one]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Wed, 18 Dec 2019 17:31:12 GMT</pubDate>
            <atom:updated>2019-12-18T21:43:25.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>Prefiero conversaciones más casuales.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*ZuNs_6pQxCdvTS_F" /><figcaption><a href="https://unsplash.com/photos/YXemfQiPR_E">Unsplash</a></figcaption></figure><p><em>Esta es una opinión muy personal — y sesgada — que puede estar equivocada o tener poco fundamento práctico, es solo eso, mi opinión.</em></p><p>En mi haber como profesional he sido liderado y me ha tocado liderar equipos y siempre he evitado seguir estrictamente las reglas guiándome más por los instintos y/o e̵l̵ mi sentido común.</p><p>Una de esas reglas — o herramienta — que he experimentado como team member y que nunca he usado como líder son las llamadas reuniones <strong>one on one.</strong> No me gusta la idea de reuniones estructuradas con tu manager u otros miembros para preguntar o responder ¿cómo va todo?, ¿qué tal tu vida?, ¿que tal el proyecto?, ¿hay algo que te esté bloqueando? ¿cómo puedo ayudarte? o me gustaría hablar de tu performance.</p><p>Si se trata de empatizar y ayudar o pedir ayuda ¿por qué hay que esperar a una reunión? y peor ¿por qué hay que prepararse para ello?</p><p>No me gustan los one on one porque personalmente nunca sé que decir. Prefiero un enfoque diferente, algo más casual, más fluido, humano, familiar, sin estructura. Yo prefiero:</p><p>(1) Especificar un horario en la semana donde estoy siempre disponible para conversar de cualquier tema (personal o profesional). Puede ser una o dos horas separado en instancias de quince minutos de forma que si más de una persona del team quiere conversar tenga chance ese día</p><p>(2) Transparentar al equipo que suelo acercarme en cualquier momento — respetando sus tiempos — para dar o pedir feedback acerca del proyecto y finalmente</p><p>(3) Hacerle saber a todo el equipo que si se trata de una urgencia siempre estaré disponible</p><p>Tener instancias para conversar con tu superior o con el liderazgo es necesario pero no hace falta nombre y cita, puede ser incluso una llamada casual en Slack.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf693fde8b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dando color a bash.]]></title>
            <link>https://medium.com/get-on-board-dev/dando-color-a-bash-3a20c9710b24?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a20c9710b24</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Sun, 22 Sep 2019 21:38:23 GMT</pubDate>
            <atom:updated>2019-09-22T21:38:23.934Z</atom:updated>
            <content:encoded><![CDATA[<h4>Bash con contexto y colores.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*7DZcsWkJT2aOokvN" /><figcaption><a href="https://unsplash.com/photos/5IHz5WhosQE">Unsplash</a></figcaption></figure><p>Cuando se trata de configurar un terminal bash prefiero un setup minimalista que usando un par de colores me de contexto de quien es el usuario conectado — siempre mis iniciales 😝— , en que path estoy y si el folder está bajo .git cual es el nombre de la rama, incluso si es que hay cambios pendientes.</p><p>Googleando y jugando llegué a una configuración que me satisface. Acá se puede ver en acción:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WtpRwKQ8SrH9wZON7yVl6A.png" /><figcaption>Bash con colores y símbolos para dar contexto.</figcaption></figure><p>jars es el usuario conectado, ~/workspace/getonbrd el path desde el directorio home, y scorecards es la rama git.</p><p>Verde significa que no hay cambios en la rama, rojo significa que algo cambió, *, + y — significan que el cambio es una modificación, una adición o una eliminación respectivamente.</p><p>Sigue <a href="https://gist.github.com/j4rs/0c276d7b72632f7044a48f4aae774c74">el fuente</a> de la porción del .bash_profile para que se vea así:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e6404b268ab02879a2c34b7bbbc3ac6/href">https://medium.com/media/5e6404b268ab02879a2c34b7bbbc3ac6/href</a></iframe><p><em>Como siempre felices de leer cualquier sugerencia. Mándalas via comentario o correo a team at getonbrd dot com</em> 🤗.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a20c9710b24" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/dando-color-a-bash-3a20c9710b24">Dando color a bash.</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Actualizando nuestro stack de producción]]></title>
            <link>https://medium.com/get-on-board-dev/actualizando-nuestro-stack-de-producci%C3%B3n-11263a9ffa8d?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/11263a9ffa8d</guid>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[herokuapp]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 15:04:59 GMT</pubDate>
            <atom:updated>2019-09-04T17:27:05.035Z</atom:updated>
            <content:encoded><![CDATA[<h4>Mejorando la redundancia para sobrevivir a los apagones.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*j_yVK2pZjGlgVAjo" /><figcaption>Unsplash by <a href="https://unsplash.com/@nasa">@nasa</a></figcaption></figure><p>Get on Board no es un servicio gratis, así que lo mínimo que podemos hacer es ofrecer un <a href="https://en.wikipedia.org/wiki/Service-level_agreement">SLA</a> decente a nuestros clientes. El sábado sufrimos una caída de aproximadamente tres horas 🤦‍♂️, y si bien el incidente fue originado en el proveedor de nuestro proveedor[1] el haber tenido una arquitectura mínima de alta disponibilidad podría haber ayudado a sobrevivir la caída o al menos a una rápida recuperación. Hacemos mea culpa de haber descuidado ciertos aspectos en nuestra arquitectura para “garantizar” esto y en respuesta hicimos cambios dentro del limitado presupuesto que tenemos 💪.</p><p>El nuevo stack consiste en:</p><ul><li><strong>2 dynos web</strong> (<em>Performance-M</em>). Antes era un solo dyno tipo <em>Performance-L</em>. El cambio a dos dynos <a href="https://devcenter.heroku.com/articles/production-check#dyno-redundancy">aumenta los chances de tener redundancia</a> — no lo garantiza — al aumentar la probabilidad de que corran en diferente infraestructura física, dígase zona <em>AWS</em>.</li><li><strong>1 dyno worker</strong> (<em>2X</em>). No le hicimos modificaciones pues no es un componente crítico. Este worker corre las tareas en background que pueden quedar guardadas en la base de datos <em>redis</em> mientras el dyno se recupera de la caída.</li><li><strong>Heroku Postgres HA</strong>. Nos mudamos a uno de los planes que brinda <a href="https://devcenter.heroku.com/articles/heroku-postgres-ha">alta disponibilidad y mecanismo de auto-failover</a>.</li><li><strong>Redis</strong> con alta disponibilidad y mecanismo de auto-failover. Acá no hicimos cambios pues ya el plan actual lo brinda.</li><li><strong>Cluster MemCache</strong> con alta disponibilidad. Acá tampoco hicimos cambios.</li></ul><p>El nuevo cambio <strong>no</strong> garantiza 100% de disponibilidad (ni siquiera gigantes como AWS o Google Cloud pueden), pero esperamos que mitigue las caídas o nos permita una recuperación más rápida.</p><p><em>Como siempre felices de leer si tienes alguna sugerencia. Mándalas via comentario o correo a team at getonbrd dot com</em> 🤗</p><p>[1] <a href="https://status.heroku.com/incidents/1892">La cosa partió</a> por problemas de conectividad en instancias <em>EC2</em> y <em>RDS</em> en la zona AWS de N. Virginia / U.S que provocó las caídas en algunos <em>dynos</em> y servicios (entre ellos <em>postgres)</em> de <em>Heroku</em> deployados en esa zona.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=11263a9ffa8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/actualizando-nuestro-stack-de-producci%C3%B3n-11263a9ffa8d">Actualizando nuestro stack de producción</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Todos los mails son iguales… pero algunos son más iguales que otros.]]></title>
            <link>https://medium.com/get-on-board-dev/todos-los-mails-son-iguales-pero-algunos-son-m%C3%A1s-iguales-que-otros-d27a47c39b13?source=rss-fdd71b0b7083------2</link>
            <guid isPermaLink="false">https://medium.com/p/d27a47c39b13</guid>
            <category><![CDATA[today-i-learned]]></category>
            <category><![CDATA[actionmailer]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jorge Rodriguez]]></dc:creator>
            <pubDate>Wed, 21 Aug 2019 18:48:44 GMT</pubDate>
            <atom:updated>2019-08-21T19:24:16.896Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*uObiGvzYa6G7WypG" /><figcaption>Unsplash by <a href="https://unsplash.com/@epicantus">Daria Nepriakhina</a></figcaption></figure><h3>Todos los mails son iguales… pero algunos son más iguales que otros</h3><h4>Cómo priorizar colas de envíos de emails</h4><p>¿Te ha pasado? Ese correo que no llega, revisas la carpeta de SPAM y nada, oh acá está, llegó, uff, finalmente… hagamos click sobre el link…, ¿what? ¿cómo que “<em>token expirado”</em>? ¿tengo que volver a pedir otro mail? Qué frustración 😖.</p><p>Todos los correos son asíncronos, pero no todos pueden tener la misma prioridad. Correos de confirmación de cuenta, invitación a registrarte, el código para poder hacer la transferencia o el magic link para hacer login <strong>deberían siempre tener mayor prioridad que correos de notificación o newsletters.</strong></p><p>Hoy aprendí que <strong>no</strong> hay forma en Rails de especificar algo tan obvio como esto 🤦🏻‍♀️ — o al menos yo no la encuentro ni Googleando — .</p><p>Entiéndase: <a href="https://guides.rubyonrails.org/action_mailer_basics.html">ActionMailer</a> permite especificar el nombre de la cola donde se almacenarán <strong>todos</strong> los correos que se quieran enviar <strong>más tarde</strong> — mediante el uso de algún sistema que soporte <a href="https://guides.rubyonrails.org/active_job_basics.html">ActiveJob</a>, dígase <em>delayed_job</em>, <em>Resque, </em>o<em> Sidekiq </em>y que por cierto es claramente una buena práctica — pero esto también significa que cada correo tendrá la misma prioridad.</p><p>Esto no es un problema si tu sistema envía unos pocos mails diarios, pero en el caso de Get on Board<em>,</em> donde todos los miércoles y domingos enviamos un <em>digest</em> personalizado a cada uno de nuestros profesionales, la cola crece inmediatamente a decenas de miles de correos encolados.</p><p>Imagina qué pasa si alguno de estos profesionales, mientras se procesa la cola, pide un <em>magic link</em> para poder iniciar sesión en Get on Board 😬 — y nos ha pasado, dicho correo tendría que esperar su turno que puede llegar a ser horas.</p><p>Lo que yo propongo es que debería existir la forma de hacer algo así:</p><pre>class NormalMailer &lt; ApplicationMailer<br>  queue :mailers</pre><pre>  def welcome(user)<br>    # send mail from our CEO welcoming the user<br>  end<br>end</pre><pre>class PriorityMailer &lt; ApplicationMailer<br>  queue :critical</pre><pre>  def magic_link(user)<br>    # send mail with the authentication token<br>  end<br>end</pre><p>Luego en el caso de <em>sidekiq, </em>bastaría especificar el orden de prioridad:</p><pre># sidekiq.yml<br>---<br>:timeout: 5<br>:concurrency: &lt;%= ENV.fetch(&#39;SIDEKIQ_MAX_THREADS&#39;) { 5 } %&gt;<br>:queues: <em># In order of priority<br>  </em>- [critical, 2]<br>  - mailers</pre><h4>Workaround</h4><p>Nuestra solución <em>in-house</em> es crear worker proxies que escuchan en colas con mayor prioridad y usan deliver_now<em> </em>para evitar encolar el mail:</p><pre>module MailWorker<br>  class CriticalMail<br>    include Sidekiq::Worker<br>    sidekiq_options queue: :critical<br>  end</pre><pre>  class SendMagicLink &lt; CriticalMail<br>    def perform(args)<br>      WebproMailer.magic_link(*args).deliver_now<br>    end<br>  end<br>end</pre><p><em>Si has pasado por esto y encontraste una mejor solución, déjanos un comentario o escríbenos directamente a team at getonbrd.com contándonos </em>🤗<em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d27a47c39b13" width="1" height="1" alt=""><hr><p><a href="https://medium.com/get-on-board-dev/todos-los-mails-son-iguales-pero-algunos-son-m%C3%A1s-iguales-que-otros-d27a47c39b13">Todos los mails son iguales… pero algunos son más iguales que otros.</a> was originally published in <a href="https://medium.com/get-on-board-dev">Get on Board Dev</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>