<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://brokenco.de//feed/by_tag/javascript.xml" rel="self" type="application/atom+xml" /><link href="https://brokenco.de//" rel="alternate" type="text/html" /><updated>2026-10-31T17:58:32+00:00</updated><id>https://brokenco.de//feed/by_tag/javascript.xml</id><title type="html">rtyler</title><subtitle>a moderately technical blog</subtitle><author><name>R. Tyler Croy</name></author><entry><title type="html">Building static binaries with TypeScript</title><link href="https://brokenco.de//2019/04/04/building-static-binaries-typescript.html" rel="alternate" type="text/html" title="Building static binaries with TypeScript" /><published>2019-04-04T00:00:00+00:00</published><updated>2019-04-04T00:00:00+00:00</updated><id>https://brokenco.de//2019/04/04/building-static-binaries-typescript</id><content type="html" xml:base="https://brokenco.de//2019/04/04/building-static-binaries-typescript.html"><![CDATA[<p>The ability to shamelessly ask stupid questions has led me to numerous
interesting projects and in some cases truly novel solutions. The
subject of this blog post fits into the first part of that equation at least. I
find the single static binaries produced by Rust and Golang to be quite compelling
for system utilities, at the same time however I am fond of writing
TypeScript. Why can’t I mix chocolate with my peanut butter?</p>

<p>You kinda can! And it kinda works!</p>

<p>I first started tinkering with a tool which I discovered while goofy-hacking months
ago: <a href="https://github.com/nexe/nexe">nexe</a>. Nexe helps turn Node applications
into single static binaries with an embedded Node runtime. I had issues with
newer style imports, which weren’t working properly with the system Nexe uses
to build its bundles. I went looking around for other options. Eventually I
stumbled into <a href="https://github.com/zeit/pkg">Pkg</a> which worked quite well!</p>

<p>Combining <code class="language-plaintext highlighter-rouge">pkg</code> with TypeScript works with the simple addition of a <code class="language-plaintext highlighter-rouge">tsc</code>
invocation before calling <code class="language-plaintext highlighter-rouge">pkg</code>. Passing in the <code class="language-plaintext highlighter-rouge">build/</code> directory containing the
compiled JavaScript files, everything “just works” and a 30-ish megabyte single
static binary is generated. I have a suspicion that <code class="language-plaintext highlighter-rouge">pkg</code> won’t work effectively
with Node packages that include native code, but haven’t yet walked into that
minefield.</p>

<hr />

<p>Are static binaries which embed Node possible, definitely! Are they a good idea
… maybe! I’m looking for more interesting projects to explore the concept in
the future, but for now it’s filed under “interesting novelties.”</p>]]></content><author><name>R. Tyler Croy</name></author><category term="typescript" /><category term="javascript" /><summary type="html"><![CDATA[The ability to shamelessly ask stupid questions has led me to numerous interesting projects and in some cases truly novel solutions. The subject of this blog post fits into the first part of that equation at least. I find the single static binaries produced by Rust and Golang to be quite compelling for system utilities, at the same time however I am fond of writing TypeScript. Why can’t I mix chocolate with my peanut butter?]]></summary></entry><entry><title type="html">Streaming HTTP data with PostgreSQL and ExpressJS</title><link href="https://brokenco.de//2018/12/06/streaming-results-node-pg.html" rel="alternate" type="text/html" title="Streaming HTTP data with PostgreSQL and ExpressJS" /><published>2018-12-06T00:00:00+00:00</published><updated>2018-12-06T00:00:00+00:00</updated><id>https://brokenco.de//2018/12/06/streaming-results-node-pg</id><content type="html" xml:base="https://brokenco.de//2018/12/06/streaming-results-node-pg.html"><![CDATA[<p>One of the <a href="https://github.com/jenkins-infra/uplink">little applications</a> which
I built earlier this year ended up more useful than I originally anticipated.
Useful enough to have hit its first performance bottleneck! Performance
problems I generally grumble “nice problem to have” which profiling and
refactoring, but in this case I know what the performance problem was, but
lacked the appropriate solution.</p>

<p>This little application, Uplink, receives anonymous telemetry information from
short-lived “trials” defined within the <a href="https://github.com/jenkinsci/jenkins">Jenkins core
application</a>. The entire end-to-end system is
defined by the design document
<a href="https://github.com/jenkinsci/jep/blob/master/jep/214/README.adoc">JEP-214</a>.
What the JEP does not describe is how we use and analyze the data on the other
end. At the moment the “data science” behind Uplink has been exporting large
dumps of JSON information from Uplink, and then bash scripting the heck out of
it. As time has gone on the amount of data ingested, and therefore exportable,
has increased quite a bit. This growth in data has required numerous iterations
on the “Export” functionality, whilst everything else remained largely
unchanged.</p>

<p><strong>First iteration</strong></p>

<p>The first cut at “export” functionality was as simple and straightforward as
possible:</p>

<ol>
  <li>Receive authorized “Export” HTTP request</li>
  <li>Send the database <code class="language-plaintext highlighter-rouge">SELECT * FROM events WHERE ...</code></li>
  <li>Receive results</li>
  <li>Format an HTTP response with the right <code class="language-plaintext highlighter-rouge">Content-Disposition</code> headers, etc.</li>
</ol>

<p>This worked for much longer than I honestly thought it would. The Node
application lives close enough to the database to retrieve large datasets
within an HTTP timeout and deliver those to the client. Once the <strong>total</strong>
dataset exceeded a couple hundred megabytes, things stopped working.</p>

<p><strong>Second iteration</strong></p>

<p>The consumer of this data was, and still is a single person wielding bash
scripts a’plenty. To keep things as simple as possible, we changed the frontend
to require that any “Export” define a date range to export. Initially the Data
Scientist™ would request a whole week at a time, and when that stopped
working, they would request individual daily exports instead. Eventually this also
stopped working, somewhere around a <em>daily</em> dataset size of a couple of hundred
megabytes.</p>

<p><strong>Third iteration</strong></p>

<p>Clearly loading big stupid <code class="language-plaintext highlighter-rouge">SELECT * FROM</code> result sets into the application to
format and serve them to clients was not scalable. For the third iteration I
resolved to implement a direct stream from the database through the web
application to the client. In effect, I wanted the PostgreSQL database
connection to give me results <em>immediately</em> which would then be written
directly to the HTTP output stream; no in-memory storage.</p>

<p>I discovered a very useful Node package to solve the first part of the problem:
<a href="https://github.com/brianc/node-pg-query-stream/#pg-query-stream">pg-query-stream</a>.
The pg-query-stream package uses a database-side cursor to avoid the need to
create large datasets in memory on the database or web application.</p>

<p>The “trick”, which to be honest isn’t a very incredible trick since Node
streams are designed to be pluggable in this way, was to connect the
<code class="language-plaintext highlighter-rouge">pg-query-stream</code> directly to ExpressJS <code class="language-plaintext highlighter-rouge">Response</code> which looks like a writable
stream. To form a proper HTTP response, the ExpressJS handler must first write
the response code and headers, for which <code class="language-plaintext highlighter-rouge">response.send()</code> will not work, so
<code class="language-plaintext highlighter-rouge">response.writeHead</code> is used instead:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">query</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">QueryStream</span><span class="p">(</span><span class="dl">'</span><span class="s1">SELECT * FROM events WHERE ...</span><span class="dl">'</span><span class="p">);</span>
<span class="kd">const</span> <span class="nx">datastream</span>  <span class="o">=</span> <span class="nx">dbConnection</span><span class="p">.</span><span class="nx">query</span><span class="p">(</span><span class="nx">query</span><span class="p">);</span>

<span class="nx">response</span><span class="p">.</span><span class="nx">writeHead</span><span class="p">(</span><span class="mi">200</span><span class="p">,</span> <span class="p">{</span>
    <span class="dl">'</span><span class="s1">Content-Disposition</span><span class="dl">'</span> <span class="p">:</span> <span class="s2">`attachment; filename=</span><span class="p">${</span><span class="nx">req</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">type</span><span class="p">}</span><span class="s2">-</span><span class="p">${</span><span class="nx">req</span><span class="p">.</span><span class="nx">body</span><span class="p">.</span><span class="nx">startDate</span><span class="p">}</span><span class="s2">.json`</span><span class="p">,</span>
    <span class="dl">'</span><span class="s1">Content-Type</span><span class="dl">'</span><span class="p">:</span> <span class="dl">'</span><span class="s1">application/json</span><span class="dl">'</span><span class="p">,</span>
<span class="p">});</span>

<span class="cm">/*
 * Pipe the data to JSONStream to convert to a proper JSON string first.
 *
 * Once it has been formatted, _then_ pipe to the ExpressJS response object
 */</span>
<span class="nx">datastream</span><span class="p">.</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">JSONStream</span><span class="p">.</span><span class="nx">stringify</span><span class="p">(</span><span class="kc">false</span><span class="p">)).</span><span class="nx">pipe</span><span class="p">(</span><span class="nx">response</span><span class="p">);</span>
<span class="nx">datastream</span><span class="p">.</span><span class="nx">on</span><span class="p">(</span><span class="dl">'</span><span class="s1">end</span><span class="dl">'</span><span class="p">,</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span> <span class="nx">response</span><span class="p">.</span><span class="nx">end</span><span class="p">();</span> <span class="p">])</span>
</code></pre></div></div>
<p>(<em>You can view the actual code used <a href="https://github.com/jenkins-infra/uplink/blob/7a4b6377552d901b850c4c39570a67dd86b0a209/src/controllers/export.ts#L19-L32">here</a></em>)</p>

<hr />

<p>This approach is, as far as I can tell, “infinitely” scalable. So long as the
database can stream data to the Node application, the Node application will
continue to write data into the response for the end-user.</p>

<p>I was so worried that I was going to have to find some way to generate bulk
files on the server with some background job processing system, or something
else equally complex. I’m thrilled that the solution simply required connecting
one streamy thing to another streamy thing, which Node is quite well suited
for.</p>

<p>Neat!</p>]]></content><author><name>R. Tyler Croy</name></author><category term="javascript" /><category term="expressjs" /><category term="postgresql" /><summary type="html"><![CDATA[One of the little applications which I built earlier this year ended up more useful than I originally anticipated. Useful enough to have hit its first performance bottleneck! Performance problems I generally grumble “nice problem to have” which profiling and refactoring, but in this case I know what the performance problem was, but lacked the appropriate solution.]]></summary></entry><entry><title type="html">Feathers authentication for web pages and forms</title><link href="https://brokenco.de//2018/09/21/feathers-form-authentication.html" rel="alternate" type="text/html" title="Feathers authentication for web pages and forms" /><published>2018-09-21T00:00:00+00:00</published><updated>2018-09-21T00:00:00+00:00</updated><id>https://brokenco.de//2018/09/21/feathers-form-authentication</id><content type="html" xml:base="https://brokenco.de//2018/09/21/feathers-form-authentication.html"><![CDATA[<p>I have been using <a href="http://feathersjs.com">Feathers</a> for a number of projects
lately, including the backend and client for <a href="https://jenkins.io/projects/evergreen">Jenkins
Evergreen</a>. 
It is obvious from the design and structure of Feathers that a significant
amount of thought went into its development.  Overall, I have been happy with
the experience implementing clean APIs, and have added Feathers as my default
toolchain for new web API and application development. Feathers has been great
for building JSON-based RESTful APIs, but I stumbled over some hurdles when
using it as a more traditional web application framework.</p>

<p>The simplest to fix, but most frustrating to stumble over, was utilizing
<a href="https://docs.feathersjs.com/api/authentication/server.html">Feathers
Authentication</a>
when serving <a href="https://docs.feathersjs.com/guides/advanced/using-a-view-engine.html">views via
Feathers</a>.
By default, the authentication in Feathers utilizes a <a href="https://jwt.io">JSON
Web Token</a> for capturing the current authentication status of a
request. When using the
<a href="https://docs.feathersjs.com/api/authentication/oauth2.html">OAuth2</a>
authentication mechanism, it is possible to tell Feathers to set a cookie with
the JSON Web Token.</p>

<p>Then, when adding authorization in front of a Feathers service, it’s as simple as
adding a hook:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span>
  <span class="nl">before</span><span class="p">:</span> <span class="p">{</span>
    <span class="na">all</span><span class="p">:</span> <span class="p">[</span>
      <span class="nx">authentication</span><span class="p">.</span><span class="nx">hooks</span><span class="p">.</span><span class="nx">authenticate</span><span class="p">([</span><span class="dl">'</span><span class="s1">jwt</span><span class="dl">'</span><span class="p">]),</span>
    <span class="p">],</span>
  <span class="p">},</span>
  <span class="nx">after</span><span class="p">:</span> <span class="p">{</span>
  <span class="p">},</span>
  <span class="nx">error</span><span class="p">:</span> <span class="p">{</span>
  <span class="p">},</span>
<span class="p">};</span>
</code></pre></div></div>

<p>Unfortunately even with that cookie set, a browser accessing the service, this
results in “Not Authentication” errors.</p>

<p>After a bit of searching around I eventually discovered some references to what
I <em>thought</em> might solve my problem on this page titled:
<a href="https://docs.feathersjs.com/guides/auth/recipe.express-middleware.html">FeathersJS Auth Recipe: Authenticating Express middleware (SSR)</a>.</p>

<p>By default, though the OAuth2 authentication module for Feathers will <em>set</em> a
cookie, it doesn’t appear to do anything by default to <em>read</em> that same cookie.
One must install and use the <code class="language-plaintext highlighter-rouge">cookie-parser</code> package.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ npm install --save cookie-parser
</code></pre></div></div>

<p>Once the <code class="language-plaintext highlighter-rouge">cookie-parser</code> package has been installed, it’s important that it
gets added as the first middleware in the application.</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">cookieParser</span> <span class="o">=</span> <span class="nx">require</span><span class="p">(</span><span class="dl">'</span><span class="s1">cookie-parser</span><span class="dl">'</span><span class="p">);</span>
<span class="cm">/*
 * Add the cookie parser to GET routes
 */</span>
<span class="nx">app</span><span class="p">.</span><span class="kd">get</span><span class="p">(</span><span class="dl">'</span><span class="s1">*</span><span class="dl">'</span><span class="p">,</span> <span class="nx">cookieParser</span><span class="p">());</span>
<span class="cm">/*
 * Add the cookie parser to POST routes
 */</span>
<span class="nx">app</span><span class="p">.</span><span class="nx">post</span><span class="p">(</span><span class="dl">'</span><span class="s1">*</span><span class="dl">'</span><span class="p">,</span> <span class="nx">cookieParser</span><span class="p">());</span>
</code></pre></div></div>

<p>With this package installed and configured, the JWT cookie will be parsed
properly when for requests coming in to the application. This ensures that the
<code class="language-plaintext highlighter-rouge">authentication.hooks.authenticate(['jwt'])</code> hook has the appropriate material
it needs to perform the authentication.</p>]]></content><author><name>R. Tyler Croy</name></author><category term="javascript" /><category term="feathersjs" /><summary type="html"><![CDATA[I have been using Feathers for a number of projects lately, including the backend and client for Jenkins Evergreen. It is obvious from the design and structure of Feathers that a significant amount of thought went into its development. Overall, I have been happy with the experience implementing clean APIs, and have added Feathers as my default toolchain for new web API and application development. Feathers has been great for building JSON-based RESTful APIs, but I stumbled over some hurdles when using it as a more traditional web application framework.]]></summary></entry><entry><title type="html">The single most important middleware for Express</title><link href="https://brokenco.de//2018/09/16/the-most-important-middleware.html" rel="alternate" type="text/html" title="The single most important middleware for Express" /><published>2018-09-16T00:00:00+00:00</published><updated>2018-09-16T00:00:00+00:00</updated><id>https://brokenco.de//2018/09/16/the-most-important-middleware</id><content type="html" xml:base="https://brokenco.de//2018/09/16/the-most-important-middleware.html"><![CDATA[<p>Almost every web framework I have used in the past five years shares the same
stupid flaw: mishandling of redundant slashes. Invariably this causes problems
when some script <em>somewhere</em> joins URL segments together with multiple slashes
in them, and ends up receiving a 404.</p>

<p>The following <a href="https://expressjs.com/">ExpressJS</a> middleware will properly neutralize redundant slashes
before the routing layer takes over.</p>

<div class="language-plaintext highlighter-rouge"><div class="highlight"><pre class="highlight"><code>  /*
   * Remove redundant slashes in the URL for properly routing
   *
   * For example: //authentication -&gt; /authentication which ensures that the
   * request is routed correctly
   */
  app.all('*', (request, response, next) =&gt; {
    request.url = request.url.replace(/\/+/, '/');
    next();
  });
</code></pre></div></div>]]></content><author><name>R. Tyler Croy</name></author><category term="javascript" /><category term="opinion" /><summary type="html"><![CDATA[Almost every web framework I have used in the past five years shares the same stupid flaw: mishandling of redundant slashes. Invariably this causes problems when some script somewhere joins URL segments together with multiple slashes in them, and ends up receiving a 404.]]></summary></entry><entry><title type="html">Exploring TypeScript</title><link href="https://brokenco.de//2018/09/01/exploring-typescript.html" rel="alternate" type="text/html" title="Exploring TypeScript" /><published>2018-09-01T00:00:00+00:00</published><updated>2018-09-01T00:00:00+00:00</updated><id>https://brokenco.de//2018/09/01/exploring-typescript</id><content type="html" xml:base="https://brokenco.de//2018/09/01/exploring-typescript.html"><![CDATA[<p>In my <a href="/2018/08/30/cd-for-the-jenkins-project.html">previous post</a> I mentioned
<a href="https://github.com/jenkins-infra/evergreen">Jenkins Evergreen</a> which requires
a significant <em>backend</em> service to built and deployed to manage a pushed-update
lifecycle. The prototype of that service which I wrote sometime late last year
was in Ruby, but I quickly realized that my usual comfort area of Ruby and
Python were not going to meet some requirements for the service. Consequently,
I ventured into JavaScript, with the fantastic framework
<a href="https://feathersjs.com">FeathersJS</a>. Almost a year later, I now have some
thoughts on the strengths and weaknesses of server-side JavaScript, and have in
turn started to explore
<a href="https://www.typescriptlang.org/">TypeScript</a>. Overall I have found TypeScript
to be interesting, but it is not without its weaknesses.</p>

<h2 id="complexity-with-external-libraries">Complexity with External Libraries</h2>

<p>When we first started building the Evergreen backend,
<a href="https://github.com/batmat">Baptiste</a> suggested TypeScript for adding helpful
types and other features to our development of Evergreen. At the time, I was
most concerned with the added complexity TypeScript might add to a project
where nobody involved was familiar with TypeScript <em>nor</em> JavaScript. Having
since started a couple of projects in TypeScript, I still believe this to be
the case, unfortunately.</p>

<p>When adding other JavaScript-based libraries to a project, they often need a
<code class="language-plaintext highlighter-rouge">@types</code> package or some other definition of what the types that package
requires for the TypeScript compiler to do proper type checking. Microsoft does
have this handy <a href="https://microsoft.github.io/TypeSearch/">TypeSearch web site</a>
which makes discovering pre-existing types-packages easier. Without a
types-package however, you may need to add type declarations into your <em>own</em>
project for third-party libraries to realize benefits of TypeScript.</p>

<p>Assuming you understand the art and zen of TypeScript, creating these type
declaration files isn’t <em>too</em> difficult, but for the novice to intermediate
user, I believe it’s still overly complex.</p>

<h2 id="testing">Testing</h2>

<p>For writing and executing JavaScript tests, I have been very happy with
<a href="https://facebook.github.io/jest">jest</a>. TypeScript and Jest <em>sort of</em> get
along together. I recommend the additional package <code class="language-plaintext highlighter-rouge">ts-jest</code> and the following
configuration in <code class="language-plaintext highlighter-rouge">package.json</code> to ensure that TypeScript is being executed
properly within tests.</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="w">  </span><span class="nl">"jest"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"transform"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
      </span><span class="nl">"^.+\\.tsx?$"</span><span class="p">:</span><span class="w"> </span><span class="s2">"ts-jest"</span><span class="w">
    </span><span class="p">},</span><span class="w">
    </span><span class="nl">"testRegex"</span><span class="p">:</span><span class="w"> </span><span class="s2">"(/test/.*|(</span><span class="se">\\</span><span class="s2">.|/)(test|spec))</span><span class="se">\\</span><span class="s2">.(jsx?|tsx?)$"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"moduleFileExtensions"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
      </span><span class="s2">"ts"</span><span class="p">,</span><span class="w">
      </span><span class="s2">"tsx"</span><span class="p">,</span><span class="w">
      </span><span class="s2">"js"</span><span class="p">,</span><span class="w">
      </span><span class="s2">"jsx"</span><span class="p">,</span><span class="w">
      </span><span class="s2">"json"</span><span class="p">,</span><span class="w">
      </span><span class="s2">"node"</span><span class="w">
    </span><span class="p">]</span><span class="w">
  </span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>The downside with <code class="language-plaintext highlighter-rouge">ts-jest</code> that I have found is that it’s not as comprehensive
as the TypeScript compiler. This results in tests running despite compilation
failures, which leads me to question what code is actually running under test.
My workaround for this is to always maintain two terminal window panes open to
the right of my editor. One with <code class="language-plaintext highlighter-rouge">tsc -w</code>, to constantly re-compile on
filesystem changes, and <code class="language-plaintext highlighter-rouge">jest --watchAll</code> to constantly re-run tests on
filesystem changes.</p>

<p>By running both of these together, I get the helpful compilation errors out of
the TypeScript compiler, while still running my tests and getting the useful
test feedback.</p>

<p>While not ideal, when <code class="language-plaintext highlighter-rouge">tsc</code> says I have compilation errors and <code class="language-plaintext highlighter-rouge">jest</code> passes my
tests, I don’t get the most confidence in those green test results.</p>

<h2 id="outputting-javascript">Outputting JavaScript</h2>

<p>TypeScript out of the box seems to target a much newer version of ECMAScript
than Node LTS (8) or latest (10) supports out of the box. For server-side
applications, I’ve found the following <code class="language-plaintext highlighter-rouge">tsconfig.json</code> to result in good
Node-compatible JavaScript:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"compilerOptions"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w">
    </span><span class="nl">"alwaysStrict"</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="p">,</span><span class="w">
    </span><span class="nl">"outDir"</span><span class="p">:</span><span class="w"> </span><span class="s2">"./build"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"module"</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="s2">"commonjs"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"skipLibCheck"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="p">,</span><span class="w">
    </span><span class="nl">"lib"</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="s2">"es2017"</span><span class="p">],</span><span class="w">
    </span><span class="nl">"module"</span><span class="p">:</span><span class="w"> </span><span class="s2">"commonjs"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"moduleResolution"</span><span class="p">:</span><span class="w"> </span><span class="s2">"node"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"esModuleInterop"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="p">,</span><span class="w">
    </span><span class="nl">"importHelpers"</span><span class="w"> </span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="p">,</span><span class="w">
    </span><span class="nl">"target"</span><span class="p">:</span><span class="w"> </span><span class="s2">"es2015"</span><span class="p">,</span><span class="w">
    </span><span class="nl">"sourceMap"</span><span class="p">:</span><span class="w"> </span><span class="kc">true</span><span class="w">
  </span><span class="p">},</span><span class="w">
  </span><span class="nl">"include"</span><span class="p">:</span><span class="w"> </span><span class="p">[</span><span class="w">
      </span><span class="s2">"./src/**/*"</span><span class="w">
  </span><span class="p">]</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Of particular note are the <code class="language-plaintext highlighter-rouge">target</code> and <code class="language-plaintext highlighter-rouge">lib</code> properties which ensure that some
modern JavaScript features are made available with an appropriate output format
which will run on Node 10. Now, what features those are specifically I can no
longer remember as that was many Stack Overflow searches ago at this point.</p>

<p>As best as I can tell, <code class="language-plaintext highlighter-rouge">tsc</code> is rather smart in that if the configuration isn’t
supposed to work with a certain version of JavaScript, than there will be
compile-time errors for some standard API calls, such as methods added to
<code class="language-plaintext highlighter-rouge">Array</code> or <code class="language-plaintext highlighter-rouge">String</code> in recent language revisions.</p>

<p>I’m not supremely comfortable cargo-culting configuration from one project to
another, but I have little interest at this point in time in understanding the
depths of how TypeScript is configured, and why one might choose various
options depending on the project’s needs.</p>

<hr />

<p>In my personal projects I have yet to truly realize the benefits of
TypeScript but I have definitely been burned by the lack thereof in other
projects. Experiencing bugs which would have been prevented in TypeScript gives
me the confidence to continue the exploration of TypeScript, despite some of
the challenges it presents.</p>

<p>In a future blog post, I hope to outline some of the challenges faced, and
patterns needed for successfully using TypeScript together with a FeathersJS
application. Honestly though, I’m not sure I’ve even figured that one out yet.
And therein lies the fundamental problem with TypeScript:</p>

<p>It’s a great add-on to the JavaScript ecosystem, but it suffers the drawbacks
of being an add-on.</p>]]></content><author><name>R. Tyler Croy</name></author><category term="javascript" /><category term="typescript" /><summary type="html"><![CDATA[In my previous post I mentioned Jenkins Evergreen which requires a significant backend service to built and deployed to manage a pushed-update lifecycle. The prototype of that service which I wrote sometime late last year was in Ruby, but I quickly realized that my usual comfort area of Ruby and Python were not going to meet some requirements for the service. Consequently, I ventured into JavaScript, with the fantastic framework FeathersJS. Almost a year later, I now have some thoughts on the strengths and weaknesses of server-side JavaScript, and have in turn started to explore TypeScript. Overall I have found TypeScript to be interesting, but it is not without its weaknesses.]]></summary></entry><entry><title type="html">Working with JavaScript callback APIs from async/await</title><link href="https://brokenco.de//2018/01/27/working-with-callbacks-and-asyncawait.html" rel="alternate" type="text/html" title="Working with JavaScript callback APIs from async/await" /><published>2018-01-27T00:00:00+00:00</published><updated>2018-01-27T00:00:00+00:00</updated><id>https://brokenco.de//2018/01/27/working-with-callbacks-and-asyncawait</id><content type="html" xml:base="https://brokenco.de//2018/01/27/working-with-callbacks-and-asyncawait.html"><![CDATA[<p>To ignore Node.js as a possibility in certain problem domains, for which it is
the best tool for the job, is a tremendously silly and at times unprofessional
decision. While I don’t delight in writing JavaScript, I must acknowledge that
JavaScript has matured quite nicely over the past ten years. Perhaps the most
helpful addition, for me at least, are the <code class="language-plaintext highlighter-rouge">async</code> and <code class="language-plaintext highlighter-rouge">await</code> keywords which
aim to prevent the callback nightmare many casual JavaScript developers may
dread.</p>

<p>Particularly for Node applications, callbacks provided a mechanism through
which highly event-driven code could be executed. Inside the runtime, this generally
means the execution thread can defer certain slow operations, such as timers or
network I/O, until the timer fires or the socket’s buffer has data available
for the application. All the while, executing other “work” within the
application. I was first introduced to this cooperative multitasking
approach over a decade ago, via “greenlets” in Python, the tools and libraries
I used were hacks on top of CPython, and never caught any significant adoption.
Node, however, is “just JavaScript” which practically every web application
must maintain some familiarity with anyways. This allowed Node to enter a
niche, which <a href="https://golang.org">Go</a> would later intrude upon, of lightweight
and high-connection-count services.</p>

<p>Unfortunately, callback-oriented code is fairly difficult to read and
understand as it’s execution-flow cannot be read linearly by scrolling down in
the text editor. For this reason, in my opinion, the <code class="language-plaintext highlighter-rouge">async</code> and <code class="language-plaintext highlighter-rouge">await</code> syntax
sugar is so valuable in JavaScript. Borrowing from
<a href="https://javascriptasyncfunction.com/">javascriptasyncfunction.com</a>,
callback-oriented code such as:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">foo</span><span class="p">(</span><span class="nx">onSuccess</span><span class="p">)</span> <span class="p">{</span>
  <span class="kd">var</span> <span class="nx">request</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">XMLHttpRequest</span><span class="p">();</span>
  <span class="nx">request</span><span class="p">.</span><span class="nx">open</span><span class="p">(</span><span class="dl">'</span><span class="s1">GET</span><span class="dl">'</span><span class="p">,</span> <span class="dl">'</span><span class="s1">https://swapi.co/api/people/1/</span><span class="dl">'</span><span class="p">,</span> <span class="kc">true</span><span class="p">);</span>

  <span class="nx">request</span><span class="p">.</span><span class="nx">onload</span> <span class="o">=</span> <span class="kd">function</span><span class="p">()</span> <span class="p">{</span>
    <span class="k">if</span> <span class="p">(</span><span class="nx">request</span><span class="p">.</span><span class="nx">status</span> <span class="o">&gt;=</span> <span class="mi">200</span> <span class="o">&amp;&amp;</span> <span class="nx">request</span><span class="p">.</span><span class="nx">status</span> <span class="o">&lt;</span> <span class="mi">400</span><span class="p">)</span> <span class="p">{</span>
      <span class="kd">var</span> <span class="nx">data</span> <span class="o">=</span> <span class="nx">JSON</span><span class="p">.</span><span class="nx">parse</span><span class="p">(</span><span class="nx">request</span><span class="p">.</span><span class="nx">responseText</span><span class="p">);</span>
      <span class="nx">onSuccess</span><span class="p">(</span><span class="nx">data</span><span class="p">.</span><span class="nx">name</span><span class="p">);</span>
    <span class="p">}</span>
  <span class="p">};</span>

  <span class="nx">request</span><span class="p">.</span><span class="nx">send</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p>Can be re-written as:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">async</span> <span class="kd">function</span> <span class="nx">foo</span><span class="p">()</span> <span class="p">{</span>
  <span class="kd">const</span> <span class="nx">response</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">fetch</span><span class="p">(</span><span class="dl">'</span><span class="s1">https://swapi.co/api/people/1/</span><span class="dl">'</span><span class="p">);</span>
  <span class="kd">const</span> <span class="nx">parsedResponse</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">response</span><span class="p">.</span><span class="nx">json</span><span class="p">();</span>
  <span class="k">return</span> <span class="nx">parsedResponse</span><span class="p">.</span><span class="nx">name</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This is all well and good, but only works because the APIs underneath, e.g.
<code class="language-plaintext highlighter-rouge">fetch</code>, have been introduced to support it. For the unfortunate developer
(read: me) who must work with the legacy “callback-oriented” APIs, it might not
be obvious how to use <code class="language-plaintext highlighter-rouge">async</code> and <code class="language-plaintext highlighter-rouge">await</code> in an application which <em>must</em>
integrate with callback-driven libraries.</p>

<hr />

<p>While banging my head against this problem I learned that JavaScript engines
introduced the <code class="language-plaintext highlighter-rouge">Promise</code> API, which was somehow related, but it was never
succinctly clear how.</p>

<p>What I found so terribly confusing was: I had always seen the <code class="language-plaintext highlighter-rouge">async</code> and
<code class="language-plaintext highlighter-rouge">await</code> keywords used together but never with a callback-oriented API.</p>

<p>It helps to tease the two apart, and explain them separately:</p>

<p><strong>async</strong>: should be used with a function declaration to denote that it can be
deferred and will, in effect, implicitly return a <code class="language-plaintext highlighter-rouge">Promise</code>.</p>

<p><strong>await</strong>: should be used to block a sequential flow of execution until a
<code class="language-plaintext highlighter-rouge">Promise</code> can be resolved. <code class="language-plaintext highlighter-rouge">await</code> cannot be used unless the function
containing it is marked <code class="language-plaintext highlighter-rouge">async</code>.</p>

<p>Let’s say I want to take a function, which currently uses callbacks, and
incorporate it into the rest of my <code class="language-plaintext highlighter-rouge">async</code>/<code class="language-plaintext highlighter-rouge">await</code> application. The trick, it
turns out, is to wrap it with a <code class="language-plaintext highlighter-rouge">Promise</code>:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">function</span> <span class="nx">sendMessage</span><span class="p">(</span><span class="nx">payload</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">return</span> <span class="k">new</span> <span class="nb">Promise</span><span class="p">((</span><span class="nx">resolveFunction</span><span class="p">,</span> <span class="nx">rejectFunction</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
        <span class="nx">clientAPI</span><span class="p">.</span><span class="nx">send</span><span class="p">(</span><span class="nx">payload</span><span class="p">,</span> <span class="p">(</span><span class="nx">error</span><span class="p">,</span> <span class="nx">response</span><span class="p">)</span> <span class="o">=&gt;</span> <span class="p">{</span>
            <span class="cm">/* in the callback */</span>

            <span class="cm">/* if there was an error, invoke the `reject` function as part of
               the Promise API. */</span>
            <span class="k">if</span> <span class="p">(</span><span class="nx">error</span><span class="p">)</span> <span class="p">{</span> <span class="nx">rejectFunction</span><span class="p">(</span><span class="nx">error</span><span class="p">);</span> <span class="p">}</span>

            <span class="cm">/* if there was a response, inoke the `resolve` function as part of
               the Promise API */</span>
            <span class="nx">resolveFunction</span><span class="p">(</span><span class="nx">response</span><span class="p">);</span>
        <span class="p">});</span>
    <span class="p">});</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This <code class="language-plaintext highlighter-rouge">sendMessage</code> function can then be used in other <code class="language-plaintext highlighter-rouge">async</code> type functions,
e.g.:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">async</span> <span class="kd">function</span> <span class="nx">notifyBroker</span><span class="p">()</span> <span class="p">{</span>
    <span class="kd">let</span> <span class="nx">response</span> <span class="o">=</span> <span class="k">await</span> <span class="nx">sendMessage</span><span class="p">({</span><span class="na">ping</span><span class="p">:</span> <span class="kc">true</span><span class="p">});</span>
    <span class="cm">/* do something with `response` */</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This doesn’t completely change the writing of JavaScript to a sequential model,
the top-level invocation of this function must treat it as a <code class="language-plaintext highlighter-rouge">Promise</code>, e.g.:
<code class="language-plaintext highlighter-rouge">notifyBroker().then(() =&gt; { /* callback when notifyBroker() completes */ });</code></p>

<p>It does, however, make it a lot easier to author non-blocking code without
a descent into callback hell.</p>]]></content><author><name>R. Tyler Croy</name></author><category term="software" /><category term="javascript" /><summary type="html"><![CDATA[To ignore Node.js as a possibility in certain problem domains, for which it is the best tool for the job, is a tremendously silly and at times unprofessional decision. While I don’t delight in writing JavaScript, I must acknowledge that JavaScript has matured quite nicely over the past ten years. Perhaps the most helpful addition, for me at least, are the async and await keywords which aim to prevent the callback nightmare many casual JavaScript developers may dread.]]></summary></entry><entry><title type="html">V8 and FastCGI, Exploring an Idea</title><link href="https://brokenco.de//2009/03/09/v8-and-fastcgi-exploring-an-idea.html" rel="alternate" type="text/html" title="V8 and FastCGI, Exploring an Idea" /><published>2009-03-09T00:00:00+00:00</published><updated>2009-03-09T00:00:00+00:00</updated><id>https://brokenco.de//2009/03/09/v8-and-fastcgi-exploring-an-idea</id><content type="html" xml:base="https://brokenco.de//2009/03/09/v8-and-fastcgi-exploring-an-idea.html"><![CDATA[Over the past couple years I've talked a lot of trash about JavaScript (really, a <strong>lot</strong>) but I've slowly started to come around to a more neutral stance, I actually hate <em>browsers</em>, I like JavaScript just fine by itself! While the prototype-based object system is a little weird at first coming from a more classical object-oriented background, the concept grows on you the more you use it.<br>
<br>
Since I hate browsers so much (I really do), I was pleased as punch to hear that <a href="http://code.google.com/p/v8/" target="_blank">Google's V8 JavaScript Engine</a> was embeddable. While WebKit's <a href="http://webkit.org/projects/javascript/" target="_blank">JavaScriptCore</a> is quite a nice JavaScript engine, it doesn't lend itself to being embedded the same way that V8 does. The only immediate downside to V8 is that it's written entirely in C++, which does provide some hurdles to embedding (for example, I'm likely never going to be able to embed it into a <a href="http://www.mono-project.com" target="_blank">Mono</a> application), but for the majority of cases embedding the engine into a project shouldn't be all that difficult. <br>
<br>
A few weekends ago I started exploring the possibility of running server-side JavaScript courtesy of V8, after reading about <a href="http://journal.paul.querna.org/articles/2008/12/23/mod_v8/" target="_blank">mod_v8</a> I felt more confident to try my project: <a href="http://github.com/rtyler/fastjs/tree/master" target="_blank"><strong>FastJS</strong></a>. <br>
<br>
In a nutshell, FastJS is a <a href="http://www.fastcgi.com/" target="_blank">FastCGI</a> server to process server-side JavaScript, this means FastJS can hook up to <a href="http://www.lighttpd.net/" target="_blank">Lighttpd</a>, <a href="http://nginx.net/" target="_blank">Nginx</a>, or even Apache via <a href="http://fastcgi.coremail.cn/" target="_blank">mod_fcgi</a>. Currently FastJS is in a state of "extremely unstable and downright difficult", there's not a lot there as I'm exploring what should be provided by the FastJS server-side software, and what should be provided by JavaScript libraries. As it stands now, FastJS preloads the environment with <a href="http://jquery.com/" target="_blank">jQuery</a> 1.3.2 and a "fastjs" object which contains some important callbacks like: <pre>fastjs.write() // write to the output stream<br>
fastjs.log() // write to the FastCGI error.lgo<br>
fastjs.source() // Include and execute other JavaScript files</pre><br>
<br>
On the server side, a typical request looks something like this (for now):<pre>2009-03-09 05:04:06: (response.c.114) Response-Header:<br>
HTTP/1.1 200 OK<br>
Transfer-Encoding: chunked<br>
Content-type: text/html<br>
X-FastJS-Request: 1<br>
X-FastJS-Process: 11515<br>
X-FastJS-Engine: V8<br>
Date: Mon, 09 Mar 2009 09:04:06 GMT<br>
Server: lighttpd/1.4.18</pre><br>
<!--break--><br>
Below is an example of the current test page "<a href="http://github.com/rtyler/fastjs/blob/fe29a4feca79a861968449be1dbd520247d6d3f3/pages/index.fjs" target="_blank">index.fjs</a>":<br>
<div style="overflow: scroll; height: 210px;"><br>
<code language="javascript"><br>
var index = new Object();<br>
<br>
index.header = function() {<br>
	fastjs.write("<html><head><title>FastJS</title></head>");<br>
	fastjs.write("<body>");<br>
	fastjs.write("<center><h2>FastJS Test Page</h2></center><br/>");<br>
};<br>
<br>
index.footer = function() { <br>
	fastjs.write("</body></html>");<br>
};<br>
<br>
index.dump_attributes = function(title, obj) {<br>
	fastjs.write("<br/><strong>");<br>
	fastjs.write(title);<br>
	fastjs.write("</strong><br/><hr/>");<br>
<br>
	for (var k in obj) {<br>
		fastjs.write(k + " = ");<br>
<br>
		if (typeof(obj[k]) != "string")<br>
			fastjs.write(typeof(obj[k]));<br>
		else<br>
			fastjs.write(obj[k]);<br>
<br>
		fastjs.write("<br/>\n");<br>
	}<br>
};<br>
<br>
(function() {<br>
	index.header();<br>
<br>
	fastjs.source("pages/test.fjs");<br>
<br>
	index.dump_attributes("window", window);<br>
	index.dump_attributes('location', location);<br>
	index.dump_attributes("fastjs.env", fastjs.env);<br>
	index.dump_attributes("fastjs.fcgi_env", fastjs.fcgi_env);<br>
<br>
<br>
	index.footer();<br>
<br>
	fastjs.log("This should go into the error.log");<br>
})();</code></div><br>
The code above generates a page that looks pretty basic, but informative nonetheless (<small>click to enlarge</small>):<center><a href="http://agentdero.cachefly.net/unethicalblogger.com/images/fastjs_testpage.jpeg" rel="lightbox"><img src="http://agentdero.cachefly.net/unethicalblogger.com/images/fastjs_testpage.jpeg" width="450"/></a></center><br>
<br>
Pretty fun in general to play with, I think I'm near on the point where I can stop writing more of my terrible C/C++ code and get back into the wonderful land of JavaScript. As it stands now, here's what still needs to be done:<ul><li>Proper handling of erroring scripts via an informative 500 page that reports on the error</li><li>Templating? Lots of fastjs.write() calls are likely to drive you mad</li><li>Performance concerns? As of now, the whole stack (jQuery + .fjs) are evaluated every page request.</li><li>Tests! I should really get around to writing some level of integration tests to make sure that FastJS is returning expected results for particular chunks of .fjs scripts</li></ul><br>
<br>
The project is hosted on GitHub right now, <a href="http://github.com/rtyler/fastjs/tree/master" target="_blank">here</a> and is under a 2-clause BSD license.]]></content><author><name>R. Tyler Croy</name></author><category term="miscellaneous" /><category term="software development" /><category term="javascript" /><summary type="html"><![CDATA[Over the past couple years I've talked a lot of trash about JavaScript (really, a lot) but I've slowly started to come around to a more neutral stance, I actually hate browsers, I like JavaScript just fine by itself! While the prototype-based object system is a little weird at first coming from a more classical object-oriented background, the concept grows on you the more you use it. Since I hate browsers so much (I really do), I was pleased as punch to hear that Google's V8 JavaScript Engine was embeddable. While WebKit's JavaScriptCore is quite a nice JavaScript engine, it doesn't lend itself to being embedded the same way that V8 does. The only immediate downside to V8 is that it's written entirely in C++, which does provide some hurdles to embedding (for example, I'm likely never going to be able to embed it into a Mono application), but for the majority of cases embedding the engine into a project shouldn't be all that difficult. A few weekends ago I started exploring the possibility of running server-side JavaScript courtesy of V8, after reading about mod_v8 I felt more confident to try my project: FastJS. In a nutshell, FastJS is a FastCGI server to process server-side JavaScript, this means FastJS can hook up to Lighttpd, Nginx, or even Apache via mod_fcgi. Currently FastJS is in a state of "extremely unstable and downright difficult", there's not a lot there as I'm exploring what should be provided by the FastJS server-side software, and what should be provided by JavaScript libraries. As it stands now, FastJS preloads the environment with jQuery 1.3.2 and a "fastjs" object which contains some important callbacks like: fastjs.write() // write to the output stream fastjs.log() // write to the FastCGI error.lgo fastjs.source() // Include and execute other JavaScript files On the server side, a typical request looks something like this (for now):2009-03-09 05:04:06: (response.c.114) Response-Header: HTTP/1.1 200 OK Transfer-Encoding: chunked Content-type: text/html X-FastJS-Request: 1 X-FastJS-Process: 11515 X-FastJS-Engine: V8 Date: Mon, 09 Mar 2009 09:04:06 GMT Server: lighttpd/1.4.18 Below is an example of the current test page "index.fjs": var index = new Object(); index.header = function() { fastjs.write("FastJS"); fastjs.write(""); fastjs.write("FastJS Test Page"); }; index.footer = function() { fastjs.write(""); }; index.dump_attributes = function(title, obj) { fastjs.write(""); fastjs.write(title); fastjs.write(""); for (var k in obj) { fastjs.write(k + " = "); if (typeof(obj[k]) != "string") fastjs.write(typeof(obj[k])); else fastjs.write(obj[k]); fastjs.write("\n"); } }; (function() { index.header(); fastjs.source("pages/test.fjs"); index.dump_attributes("window", window); index.dump_attributes('location', location); index.dump_attributes("fastjs.env", fastjs.env); index.dump_attributes("fastjs.fcgi_env", fastjs.fcgi_env); index.footer(); fastjs.log("This should go into the error.log"); })(); The code above generates a page that looks pretty basic, but informative nonetheless (click to enlarge): Pretty fun in general to play with, I think I'm near on the point where I can stop writing more of my terrible C/C++ code and get back into the wonderful land of JavaScript. As it stands now, here's what still needs to be done:Proper handling of erroring scripts via an informative 500 page that reports on the errorTemplating? Lots of fastjs.write() calls are likely to drive you madPerformance concerns? As of now, the whole stack (jQuery + .fjs) are evaluated every page request.Tests! I should really get around to writing some level of integration tests to make sure that FastJS is returning expected results for particular chunks of .fjs scripts The project is hosted on GitHub right now, here and is under a 2-clause BSD license.]]></summary></entry><entry><title type="html">Lazily loading attributes.</title><link href="https://brokenco.de//2008/09/15/lazily-loading-attributes.html" rel="alternate" type="text/html" title="Lazily loading attributes." /><published>2008-09-15T00:00:00+00:00</published><updated>2008-09-15T00:00:00+00:00</updated><id>https://brokenco.de//2008/09/15/lazily-loading-attributes</id><content type="html" xml:base="https://brokenco.de//2008/09/15/lazily-loading-attributes.html"><![CDATA[I found myself talking to <a href="http://jasonrubenstein.blogspot.com/" target="_blank">Jason</a> today about the virtues of <code>getattr()</code>, <code>setattr()</code>, and <code>hasattr()</code> in Python and "abusing" the dynamic nature of the language which reminded me of some lazy-loading code I wrote a while back. In February I found the need to have portions of the logic behind one of our web applications fetch data once per-request. The nature of the web applications we're building on top of the <a href="http://developer.myspace.com/community/" target="_blank">MySpace</a>, <A href="http://developer.hi5.com/" target="_blank">Hi5</a> and <a href="http://developers.facebook.com/" target="_blank">Facebook</a> platforms require some level of network data-access (traditionally via REST-like APIs). This breaks our data access model into the following tiers:<center><img src="http://agentdero.cachefly.net/unethicalblogger.com/images/data_model.png" alt=" Dia FTW "/></center> <br>
Working with network-centric data resources is difficult in any scenario (desktop, mobile, web) but the particularly difficult thing about network data access in the mod_python-driven request model is that it will be synchronous (mod_python doesn't support "<a href="http://msdn.microsoft.com/en-us/magazine/cc163725.aspx" target="_blank">asynchronous pages</a>" like ASP.NET does). This means <strong>every</strong> REST call to Facebook, for example, is going to block execution of the request handler until the REST request to Facebook's API tier completes. <code type="python"><br>
 def request_handler(self, *args, **kwargs):<br>
    fb_uid = kwargs.get('fb_sig_user')<br>
    print "Fetching the name for %s" % fb_uid<br>
    print time.time()<br>
    name = facebook.users.getInfo(uid=fb_uid) <br>
    ### WAIT-WAIT-WAIT-WAIT-WAIT<br>
    print time.time()      <br>
    ### Continue generating the page...<br>
</code>There is also a network hit (albeit minor) for accessing cached data or data stored in databases. The general idea is that we'll need to have some level of data resident in memory through-out a request that can differ widely from request-to-request.<br>
<br>
<h3>Lazy loading in Python</h3> To help avoid unnecessary database access or network access I wrote a bit of class-sugar to make this a bit easier and more fail-proof:<code type="python"><br>
class LazyProgrammer(object):<br>
    ''' <br>
        LazyProgrammer allows for lazily-loaded attributes on the subclasses <br>
        of this object. In order to enable lazily-loaded attributes define<br>
        "_X_attr_init()" for the attribute "obj.X"<br>
    '''<br>
    def __getattr__(self, name):<br>
        rc = object.__getattribute__(self, '_%s_attr_init')()<br>
        setattr(self, name, rc) <br>
        return rc<br>
</code>This makes developing with network-centric web applications a bit easier, for example, if I have a "friends" lazily-loading attribute off the base "FacebookRequest" class, all developers writing code subclassing FacebookRequest can simply refer to <code>self.friends</code> and feel confident they aren't incurring unnecessary bandwidth hits, and the friends-list fetching code is located in once spot. If one-per-request starts to become too resource intensive as well, it'd be trivial to override the <code>_friends_attr_init()</code> method to hit a caching server instead of the REST servers first, without needing to change any code "downstream."<br>
<br/><br>
<h3>Lazy loading in C#</h3> Since C# is not a dynamically-typed language like Python or JavaScript, you can't implement lazily-loaded attributes in the same fashion (calling something like <code>setattr()</code>) but you can "abuse" properties in a manner similar to the C# singleton pattern, to get the desired effect:<code type="c#"><br>
using System;<br>
using System.Collections.Generic;<br>
<br>
public class LazySharp<br>
{<br>
	#region "Lazy Members"<br>
	private Dictionary<int, string> _names = null;<br>
	#endregion<br>
<br>
	#region "Lazy Properties"<br>
	public Dictionary<int, string> Names<br>
	{<br>
		get {<br>
			if (this._names == null)<br>
				this._names = this.SomeExpensiveCall();<br>
			return this._names;<br>
		}<br>
	}<br>
	#endregion<br>
}</code>Admittedly I don't find myself writing Facebook/MySpace/Hi5 applications these days on top of ASP.NET so I cannot say I actually <em>use</em> the class above in production, but conceptually it makes sense.<br>
<br>
Lazy loading attributes I find useful in the more hodge-podge situations, where code and feature-sets have both grown organically over time, they're not for everybody but I figured I'd share anyways.]]></content><author><name>R. Tyler Croy</name></author><category term="mono" /><category term="miscellaneous" /><category term="javascript" /><summary type="html"><![CDATA[I found myself talking to Jason today about the virtues of getattr(), setattr(), and hasattr() in Python and "abusing" the dynamic nature of the language which reminded me of some lazy-loading code I wrote a while back. In February I found the need to have portions of the logic behind one of our web applications fetch data once per-request. The nature of the web applications we're building on top of the MySpace, Hi5 and Facebook platforms require some level of network data-access (traditionally via REST-like APIs). This breaks our data access model into the following tiers: Working with network-centric data resources is difficult in any scenario (desktop, mobile, web) but the particularly difficult thing about network data access in the mod_python-driven request model is that it will be synchronous (mod_python doesn't support "asynchronous pages" like ASP.NET does). This means every REST call to Facebook, for example, is going to block execution of the request handler until the REST request to Facebook's API tier completes. def request_handler(self, *args, **kwargs): fb_uid = kwargs.get('fb_sig_user') print "Fetching the name for %s" % fb_uid print time.time() name = facebook.users.getInfo(uid=fb_uid) ### WAIT-WAIT-WAIT-WAIT-WAIT print time.time() ### Continue generating the page... There is also a network hit (albeit minor) for accessing cached data or data stored in databases. The general idea is that we'll need to have some level of data resident in memory through-out a request that can differ widely from request-to-request. Lazy loading in Python To help avoid unnecessary database access or network access I wrote a bit of class-sugar to make this a bit easier and more fail-proof: class LazyProgrammer(object): ''' LazyProgrammer allows for lazily-loaded attributes on the subclasses of this object. In order to enable lazily-loaded attributes define "_X_attr_init()" for the attribute "obj.X" ''' def __getattr__(self, name): rc = object.__getattribute__(self, '_%s_attr_init')() setattr(self, name, rc) return rc This makes developing with network-centric web applications a bit easier, for example, if I have a "friends" lazily-loading attribute off the base "FacebookRequest" class, all developers writing code subclassing FacebookRequest can simply refer to self.friends and feel confident they aren't incurring unnecessary bandwidth hits, and the friends-list fetching code is located in once spot. If one-per-request starts to become too resource intensive as well, it'd be trivial to override the _friends_attr_init() method to hit a caching server instead of the REST servers first, without needing to change any code "downstream." Lazy loading in C# Since C# is not a dynamically-typed language like Python or JavaScript, you can't implement lazily-loaded attributes in the same fashion (calling something like setattr()) but you can "abuse" properties in a manner similar to the C# singleton pattern, to get the desired effect: using System; using System.Collections.Generic; public class LazySharp { #region "Lazy Members" private Dictionary _names = null; #endregion #region "Lazy Properties" public Dictionary Names { get { if (this._names == null) this._names = this.SomeExpensiveCall(); return this._names; } } #endregion }Admittedly I don't find myself writing Facebook/MySpace/Hi5 applications these days on top of ASP.NET so I cannot say I actually use the class above in production, but conceptually it makes sense. Lazy loading attributes I find useful in the more hodge-podge situations, where code and feature-sets have both grown organically over time, they're not for everybody but I figured I'd share anyways.]]></summary></entry><entry><title type="html">Resurgange of the shell.</title><link href="https://brokenco.de//2008/09/11/resurgange-of-the-shell.html" rel="alternate" type="text/html" title="Resurgange of the shell." /><published>2008-09-11T00:00:00+00:00</published><updated>2008-09-11T00:00:00+00:00</updated><id>https://brokenco.de//2008/09/11/resurgange-of-the-shell</id><content type="html" xml:base="https://brokenco.de//2008/09/11/resurgange-of-the-shell.html"><![CDATA[Two things happened in such short proximity time-wise that I can't help but thing they're somehow related to the larger shift to <em>interpreters</em>. Earlier this week Miguel introduced <a href="http://tirania.org/blog/archive/2008/Sep-08.html" target="_blank">csharp shell</a> which forced me to dust off my shoddy Mono 1.9 build and rebuild Mono from Subversion just because this is too interesting to pass up on.<br>
<br>
One of my favorite aspects of using IronPyhton, or Python for that matter is the interpreter which allows for prototyping that doesn't involve creating little test apps that I have to build to prove a point. For example, I can work through fetching a web page in the csharp shell really easily, instead of creating a silly little application, compiling, fixing errors, and recompiling:<br>
<code type="bash"><br>
tyler@pineapple:~/source/mono-project/mono> csharp<br>
Mono C# Shell, type "help;" for help<br>
<br>
Enter statements below.<br>
csharp> using System;<br>
csharp> Console.WriteLine("This changes everything.");<br>
This changes everything.<br>
csharp> String url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl";<br>
csharp> using System.Web;<br>
csharp> using System.Net;<br>
csharp> using System.IO;<br>
csharp> using System.Text;<br>
csharp> HttpWebRequest req = HttpWebRequest.Create(url);<br>
<interactive>(1,17): error CS0266: Cannot implicitly convert type `System.Net.WebRequest' to `System.Net.HttpWebRequest'. An explicit conversion exists (are you missing a cast?)<br>
csharp> HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest;<br>
csharp> HttpWebResponse response = req.GetResponse() as HttpWebResponse;<br>
csharp> StreamReader reader = new StreamReader(req.GetResponseStream() as Stream, Encoding.UTF8);<br>
<interactive>(1,45): error CS1061: Type `System.Net.HttpWebRequest' does not contain a definition for `GetResponseStream' and no extension method `GetResponseStream' of type `System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?)<br>
csharp> StreamReader reader = new StreamReader(response.GetResponseStream() as Stream, Encoding.UTF8);<br>
csharp> String result = reader.ReadToEnd();<br>
csharp> Console.WriteLine(result);<br>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN><br>
<html><br>
<body><br>
<TITLE>What time is it?</TITLE><br>
<H2> US Naval Observatory Master Clock Time</H2> <H3><br>
<BR>Sep. 11, 07:29:02 UTC<br>
<BR>Sep. 11, 03:29:02 AM EDT<br>
<BR>Sep. 11, 02:29:02 AM CDT<br>
<BR>Sep. 11, 01:29:02 AM MDT<br>
<BR>Sep. 11, 12:29:02 AM PDT<br>
<BR>Sep. 10, 11:29:02 PM AKDT<br>
<BR>Sep. 10, 09:29:02 PM HAST<br>
</H3><P><A HREF="http://tycho.usno.navy.mil">Time Service Department, US Naval Observatory</A><br>
<br>
</body></html><br>
csharp> reader.Close();<br>
csharp> response.Close();<br>
csharp>  <br>
</code><br>
<!--break--><br>
I really think Miguel and Co. have adding something infinitely more useful in this Hackweek project than anything I've seen come out of recent hackweeks at Novell. The only feature request that I'd add along to the csharp shell would be "recording", i.e.:<br>
<code type="bash"><br>
tyler@pineapple:~/source/mono-project/mono> csharp<br>
Mono C# Shell, type "help;" for help<br>
<br>
Enter statements below.<br>
csharp> Shell.record("public void Main(string[] args)");<br>
recording...<br>
csharp> using System;<br>
csharp> Console.WriteLien("I prototyped this in csharp shell!");<br>
<interactive>(1,10): error CS0117: `System.Console' does not contain a definition for `WriteLien'<br>
/home/tyler/basket/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error)<br>
csharp> Console.WriteLine("I prototyped this in csharp shell!");<br>
csharp> Shell.save_record("Hello.cs");<br>
recording saved to "Hello.cs"<br>
</code>Which could conceptually generate the following file:<code type="c#"><br>
using System;<br>
<br>
public class Hello<br>
{<br>
   public void Main(string[] args)<br>
   {<br>
     Console.WriteLine("I prototyped this in csharp shell!");<br>
   }<br>
}<br>
</code><br>
<br>
<br>
<h3>JavaScript Shell</h3>In addition to the C# shell, I've been playing with <a href="http://code.google.com/p/v8/" target="_blank">v8</a>, the JavaScript engine that powers Google Chrome. The V8 engine is capable of being embedded easily, or running standalone, one of the examples they ship with is a JavaScript shell. I've created a little wrapper script to give me the ability to load jQuery into the V8 shell to prototype jQuery code without requiring a browser to be up and running:<br>
<code type="bash"><br>
tyler@pineapple:~/source/v8> ./shell<br>
V8 version 0.3.0<br>
> load("window-compat.js");<br>
> load("jquery.js");<br>
> $ = window.$<br>
function (selector,context){return new jQuery.fn.init(selector,context);}<br>
> x = [1, 5, 6, 12, 42];<br>
1,5,6,12,42<br>
> $.each(x, function(index) { print("x[" + index + "] = " + this); });<br>
x[0] = 1<br>
x[1] = 5<br>
x[2] = 6<br>
x[3] = 12<br>
x[4] = 42<br>
1,5,6,12,42<br>
> <br>
</code>The contents of "window-compat.js" being:<br>
<code type="javascript"><br>
/*<br>
 * Providing stub "window" objects for jQuery<br>
 */<br>
<br>
if (typeof(window) == 'undefined') {<br>
        window = new Object();<br>
        document = window;<br>
        self = window;<br>
<br>
        navigator = new Object();<br>
        navigator.userAgent = navigator.userAgent || 'Chrome v8 Shell';<br>
<br>
        location = new Object();<br>
        location.href = 'file:///dev/null';<br>
        location.protocol = 'file:';<br>
        location.host = ''; <br>
};<br>
</code><br>
<br>
In general I don't really have anything insightful or especially interesting to add, but I wanted to put out my "+1" in support of both of these projects. Making any language or API more easily accessible through these shells/interpreters can really help developers double-check syntax, expected API behavior etc. Thanks Novell/Google, interpreters rock!]]></content><author><name>R. Tyler Croy</name></author><category term="mono" /><category term="javascript" /><summary type="html"><![CDATA[Two things happened in such short proximity time-wise that I can't help but thing they're somehow related to the larger shift to interpreters. Earlier this week Miguel introduced csharp shell which forced me to dust off my shoddy Mono 1.9 build and rebuild Mono from Subversion just because this is too interesting to pass up on. One of my favorite aspects of using IronPyhton, or Python for that matter is the interpreter which allows for prototyping that doesn't involve creating little test apps that I have to build to prove a point. For example, I can work through fetching a web page in the csharp shell really easily, instead of creating a silly little application, compiling, fixing errors, and recompiling: tyler@pineapple:~/source/mono-project/mono> csharp Mono C# Shell, type "help;" for help Enter statements below. csharp> using System; csharp> Console.WriteLine("This changes everything."); This changes everything. csharp> String url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"; csharp> using System.Web; csharp> using System.Net; csharp> using System.IO; csharp> using System.Text; csharp> HttpWebRequest req = HttpWebRequest.Create(url); (1,17): error CS0266: Cannot implicitly convert type `System.Net.WebRequest' to `System.Net.HttpWebRequest'. An explicit conversion exists (are you missing a cast?) csharp> HttpWebRequest req = HttpWebRequest.Create(url) as HttpWebRequest; csharp> HttpWebResponse response = req.GetResponse() as HttpWebResponse; csharp> StreamReader reader = new StreamReader(req.GetResponseStream() as Stream, Encoding.UTF8); (1,45): error CS1061: Type `System.Net.HttpWebRequest' does not contain a definition for `GetResponseStream' and no extension method `GetResponseStream' of type `System.Net.HttpWebRequest' could be found (are you missing a using directive or an assembly reference?) csharp> StreamReader reader = new StreamReader(response.GetResponseStream() as Stream, Encoding.UTF8); csharp> String result = reader.ReadToEnd(); csharp> Console.WriteLine(result); What time is it? US Naval Observatory Master Clock Time Sep. 11, 07:29:02 UTC Sep. 11, 03:29:02 AM EDT Sep. 11, 02:29:02 AM CDT Sep. 11, 01:29:02 AM MDT Sep. 11, 12:29:02 AM PDT Sep. 10, 11:29:02 PM AKDT Sep. 10, 09:29:02 PM HAST Time Service Department, US Naval Observatory csharp> reader.Close(); csharp> response.Close(); csharp> I really think Miguel and Co. have adding something infinitely more useful in this Hackweek project than anything I've seen come out of recent hackweeks at Novell. The only feature request that I'd add along to the csharp shell would be "recording", i.e.: tyler@pineapple:~/source/mono-project/mono> csharp Mono C# Shell, type "help;" for help Enter statements below. csharp> Shell.record("public void Main(string[] args)"); recording... csharp> using System; csharp> Console.WriteLien("I prototyped this in csharp shell!"); (1,10): error CS0117: `System.Console' does not contain a definition for `WriteLien' /home/tyler/basket/lib/mono/2.0/mscorlib.dll (Location of the symbol related to previous error) csharp> Console.WriteLine("I prototyped this in csharp shell!"); csharp> Shell.save_record("Hello.cs"); recording saved to "Hello.cs" Which could conceptually generate the following file: using System; public class Hello { public void Main(string[] args) { Console.WriteLine("I prototyped this in csharp shell!"); } } JavaScript ShellIn addition to the C# shell, I've been playing with v8, the JavaScript engine that powers Google Chrome. The V8 engine is capable of being embedded easily, or running standalone, one of the examples they ship with is a JavaScript shell. I've created a little wrapper script to give me the ability to load jQuery into the V8 shell to prototype jQuery code without requiring a browser to be up and running: tyler@pineapple:~/source/v8> ./shell V8 version 0.3.0 > load("window-compat.js"); > load("jquery.js"); > $ = window.$ function (selector,context){return new jQuery.fn.init(selector,context);} > x = [1, 5, 6, 12, 42]; 1,5,6,12,42 > $.each(x, function(index) { print("x[" + index + "] = " + this); }); x[0] = 1 x[1] = 5 x[2] = 6 x[3] = 12 x[4] = 42 1,5,6,12,42 > The contents of "window-compat.js" being: /* * Providing stub "window" objects for jQuery */ if (typeof(window) == 'undefined') { window = new Object(); document = window; self = window; navigator = new Object(); navigator.userAgent = navigator.userAgent || 'Chrome v8 Shell'; location = new Object(); location.href = 'file:///dev/null'; location.protocol = 'file:'; location.host = ''; }; In general I don't really have anything insightful or especially interesting to add, but I wanted to put out my "+1" in support of both of these projects. Making any language or API more easily accessible through these shells/interpreters can really help developers double-check syntax, expected API behavior etc. Thanks Novell/Google, interpreters rock!]]></summary></entry><entry><title type="html">Data Binding with jQuery</title><link href="https://brokenco.de//2008/04/02/data-binding-with-jquery.html" rel="alternate" type="text/html" title="Data Binding with jQuery" /><published>2008-04-02T00:00:00+00:00</published><updated>2008-04-02T00:00:00+00:00</updated><id>https://brokenco.de//2008/04/02/data-binding-with-jquery</id><content type="html" xml:base="https://brokenco.de//2008/04/02/data-binding-with-jquery.html"><![CDATA[Since I've come from the land of desktop application development, there are a few concepts that I don't think quite "made the voyage" from desktop/thick-client development to web/thin-client development. The concept of "data binding" is completely lost in my opinion in the land of Javascript and HTML (not to mention the concept of "controls" to begin with).A few weeks ago while exploring a couple other concepts for how to improve our overall frontend development at <a href="http://slide.com" target="_blank">Slide</a> I prototyped a means of "databinding" controls, or at the very least DOM elements to data-providing Javascript functions.<br>
<br>
I've posted <a href="http://tyler.geekisp.com/binding.html" target="_blank">an example here</a> of some of the data binding code I've written for experimentation purposes. In the example page linked, there is a &lt;ul&gt; tag that is "bound" to a Javascript function, the Javascript function creates an array of associative arrays inline (it could very well be powered by some AJAX-oriented Javascript with minor adjustments). Using the results of the "databind" function specified on the bindable element, it creates a set of child nodes to attach to the parent list. In effect, the following code:<code language="html"><br>
<script type="text/javascript"><br>
    var bindSimpleList = function() {<br>
        var simple_list = new Array();<br>
        simple_list.push({'contents' : 'List Item #1 OMG', 'onclick' : function() { alert("You clicked the first list item! lulz"); }});<br>
        simple_list.push({'contents' : 'List Item #2', 'style' : 'border-bottom: 1px dashed red; width: 100px;'});<br>
        simple_list.push({'contents' : '<strong>List Item #3</strong>'});<br>
        return simple_list;<br>
    }<br>
</script><br>
<ul class="bindable" databind="bindSimpleList" databindto="li"</ul><br>
</ul><br>
</code>Will generate the following DOM tree, after the "<strong>bind()</strong>" function has been run on page load:<code language="html"><br>
<ul class="bindable" databind="bindSimpleList" databindto="li"><br>
    <li onclick="alert('You clicked the first list item! lulz');">List Item #1 OMG</li><br>
    <li style="border-bottom: 1px dashed red; width: 100px;">List Item #2</li><br>
    <li><strong>List Item #3</strong></li><br>
</ul><br>
</code><br>
<br>
Since the code is relatively simple (in my opinion) I figured I would throw it out there in all it's minimalistic glory and get some general feedback on the concept before I go "all out" and create a full-on jQuery extension based off of the linked prototype above. I'm trying to think of ways to make it more powerful as well, built-in support for binding to the results of an asynchrounous call to a URL that returns JSON that would then create the elements is at the top of my TODO list at this point. Feedback, flames and actual useful critiques are all welcome; I'll be sure to post again once I have the time to create the jQuery extension for binding, this however is more experimental quality (i.e. don't use it, i'm not).<br>
<br>
What do you think?<br/><br>
<hr/><br>
<em>Did you know!</em> <a href="http://www.slide.com/static/jobs">Slide is hiring</a>! Looking for talented engineers to write some good Python and/or JavaScript, feel free to contact me at tyler[at]<a href="http://slide.com">slide</a><br>
<!--break--><br>]]></content><author><name>R. Tyler Croy</name></author><category term="slide" /><category term="miscellaneous" /><category term="javascript" /><summary type="html"><![CDATA[Since I've come from the land of desktop application development, there are a few concepts that I don't think quite "made the voyage" from desktop/thick-client development to web/thin-client development. The concept of "data binding" is completely lost in my opinion in the land of Javascript and HTML (not to mention the concept of "controls" to begin with).A few weeks ago while exploring a couple other concepts for how to improve our overall frontend development at Slide I prototyped a means of "databinding" controls, or at the very least DOM elements to data-providing Javascript functions. I've posted an example here of some of the data binding code I've written for experimentation purposes. In the example page linked, there is a &lt;ul&gt; tag that is "bound" to a Javascript function, the Javascript function creates an array of associative arrays inline (it could very well be powered by some AJAX-oriented Javascript with minor adjustments). Using the results of the "databind" function specified on the bindable element, it creates a set of child nodes to attach to the parent list. In effect, the following code: Will generate the following DOM tree, after the "bind()" function has been run on page load: List Item #1 OMG List Item #2 List Item #3 Since the code is relatively simple (in my opinion) I figured I would throw it out there in all it's minimalistic glory and get some general feedback on the concept before I go "all out" and create a full-on jQuery extension based off of the linked prototype above. I'm trying to think of ways to make it more powerful as well, built-in support for binding to the results of an asynchrounous call to a URL that returns JSON that would then create the elements is at the top of my TODO list at this point. Feedback, flames and actual useful critiques are all welcome; I'll be sure to post again once I have the time to create the jQuery extension for binding, this however is more experimental quality (i.e. don't use it, i'm not). What do you think? Did you know! Slide is hiring! Looking for talented engineers to write some good Python and/or JavaScript, feel free to contact me at tyler[at]slide]]></summary></entry></feed>