Showing posts with label spike. Show all posts
Showing posts with label spike. Show all posts

Thursday, October 3, 2013

What's Better Than One Polymer Element?


Having gotten the <ice-code-editor> element working in Polymer.dart, I would like to see if it is possible to get two instances of the element on the same page. Something like this would be very useful in a tutorial. The first element could contain an early version of the project, with subsequent elements containing more and more sophistication.

I have some reason to expect this work in the underlying ICE Code Editor. I spent some time getting multiple versions of the editor working to better support testing. Of course none of the tests ever explicitly tried to run two instances at the same time, but what could go wrong?

I kinda feel like spiking this rather than driving a feature via tests. So, in the sample page, I add a second custom element:
<p>
asdf asdf as df sadf as df asdf
</p>

<ice-code-editor src="embed_a.html" line_number="21"></ice-code-editor>

<p>
asdfsadfasd sadf asdf  sdf asdf a sdfsfd
</p>

<ice-code-editor src="embed_b.html" line_number="49"></ice-code-editor>

<p>
asdfsadfasd sadf asdf  sdf asdf a sdfsfd
</p>
Naturally, that does not work. I get a lovely “null object does not have a method” stack trace:



This seems not so much a Polymer issue as it is a js-interop concern. The error is being thrown from the js-interop code that wraps the JavaScript ACE editor:
class Ace extends jsw.TypedProxy {
  static Ace edit(dynamic el) => Ace.cast(js.context['ace'].edit(el));
  // ...
}
Specifically, the js.context['ace'] property is null in the second Polymer instance. My first thought is to despair that the js-interop context created by the first element is not valid in the second instance. But this does not explain how I can create 150 separate instances in my tests. Even though those test instances are never active at the same time, they all reuse the same js.context['ace'] to create the editor part of ICE.

This leads me to suspect a simple timing issue. Specifically, I believe that when the second <ice-code-editor> tag is created, the ACE JavaScript code is not loaded and evaluated. Even though it is not evaluated, ICE can tell that it has been loaded by virtue of checking for a <script> tag with a source of ace.js. Seeing that tag, ICE assumes that ACE is loaded and evaluated. This is a fine assumption in tests, but is not valid in this case.

To try out my theory, I add a simple 100 millisecond delay to ICE when it believes the JavaScript editor to already be loaded:
_startAce() {
    if (_isAceJsAttached) {
      new Timer(
        new Duration(milliseconds: 100),
        _startJsAce
      );
    }
    else {
      // Load ace.js for the first time...
    }
  }
And that seems to do the trick. I now have two different <ice-code-editor> elements running two different Three.js simulations and scrolled to different lines in the code:



Not only does it work, but the two tags seem to be completely separate. Updates to one editor only update the simulation in that instance—the preview in the other editor remains unchanged. This ought to be expected when everything is kept in the shadow DOM in Polymer elements, but I cannot keep the JavaScript code in the shadow DOM. So there was a fear that problems would arise thanks to the shared JavaScript. Happily, this does not seem to be the case.

The timer-based solution is inappropriate for real-world usage. There may be high latency cases in which 100ms is not sufficient. I think that I will back out tonight's changes and TDD the correct behavior—possibly with a static completer—tomorrow. But, for now, this was a successful spike—it seems as though this is gonna work quite nicely.


Day #893

Wednesday, July 14, 2010

Spike a New (Fab) App

‹prev | My Chain | next›

Before moving on with my (fab) game, I have a quick look at my fab.js apps dealing with the player store. Hoepfully, I might be able to clean them up or, better yet, get some test coverage for them.

Much of the player store code is wrapped in my if_body (fab) app or in the comet_view resource which establishes the comet session and adds players to the game:
  ( /chat/ )
( if_body(
function () {
var msg = JSON.parse(this.toString());
msg.body = msg.say.substr(0,100);
broadcast(comet_player_say(JSON.stringify(msg)));
} ) )

( /bounce/ )
( if_body(
function () {
update_player_status(JSON.parse(""+this));
broadcast(comet_bounce_player(this));
} ) )

( /^\/comet_view/ )
( broadcast_new )
( store_player )
( init_comet )
( player_from_querystring )
The if_body (fab) app fires the supplied function if the downstream (i.e. browser) supplied a body, which it would do by POSTing data. What I notice while looking through the store_player and init_comet apps is that I do a lot of if-response-body-then-do:
function init_comet (app) {
return function () {
var out = this;

return app.call( function listener(obj) {
if (obj && obj.body && obj.body.uniq_id) {
do_comet.call(out, obj);
}
else if (obj && obj.status) {
out(obj)();
}

return listener;
});
};
}
It could be especially helpful to factor that out of the player store code. Doing so would allow me to separate the player store entirely from the (fab) apps:
function store_player (app) {
return function () {
var out = this;

return app.call( function listener(obj) {
if (obj && obj.body && obj.body.id) {
var new_id = obj.body.id;
if (!players[new_id]) {
puts("[store_player] adding: " + new_id);
// player store code here
}
else if (players[new_id].uniq_id == obj.body.uniq_id) {
puts("[store_player] refreshing session: " + new_id);
// player store code here
}
else {
out();
}

}
out(obj);

return listener;
});
};
}
I do not think that I need a ternary (fab) app. What I need is a (fab) app that takes a callback to fire if there is a downstream response. Fab.js already includes fab.tap that does something similar, except that it does not include the downstream response when invoking the callback. The fab.tap app takes the callback as an argument, then returns a binary app:
exports.app = function( fn ) {
return function( app ) {
return function() {
fn();
return app.call( this );
}
}
}
To get the upstream response, it is not sufficient to app.call() the upstream app with the downstream listener (always set to this by fab.js). Instead, I have to app.call with a listener for the upstream response:
function if_response(fn) {
return function(app) {
return function() {
var out = this;

return app.call(function listener(obj) {
if (obj && obj.body) {
fn.call(out, obj.body);
}
out(obj);

return listener;
}
);
};
};
}
With that, I can refactor the store_player function as a side-effect only function. This allows me to rewrite the comet call stack as:
  ( /^\/comet_view/ )
( broadcast_new )
( if_response (store_player) )

( init_comet )
( player_from_querystring )
I am not sure how I feel about that syntax, so I will stop there for today. If I decide that I like it after sleeping on it, I will delete this exploratory code and BDD the real thing. Otherwise I will move onto to other matters.


Day #164

Tuesday, October 6, 2009

Rack Image Science: A Spike

‹prev | My Chain | next›

I started a spike last night to help me understand what was needed to thumbnail images in Rack. The idea is that, given a request for an image ending in _sm.jpg, the handler should request the full-sized image, thumbnail it, and return the smaller image to the requesting client.

I was actually pretty close last night, but sleepiness eventually got the better of me. This is a functioning version of last night's thumbnailer:
class ThumbNail
def initialize(app); @app = app end
def call(env)

if env['REQUEST_URI'] =~ /_sm.jpe?g/
env['REQUEST_URI'].sub!(/_sm\./, '.')
env['REQUEST_PATH'].sub!(/_sm\./, '.')
env['PATH_INFO'].sub!(/_sm\./, '.')
http_code, headers, original_body = @app.call(env)

img_data = ''
body.each do |data|
img_data << data
end


ImageScience.with_image_from_memory(img_data) do |img|
img.resize(100, 150) do |small|
small.save "/tmp/small.jpg"
end
end

f = File.open "/tmp/small.jpg"
[http_code, headers, f.read]
else
@app.call(env)
end
end
end

use ThumbNail
Missing last night was the bold section, where I actually use the body response from a Rack application like it is supposed to be used—with an each iteration.

I could delete the code and start on implementation proper, but first I would like to explore building a cache for the thumbnails. There is no sense in generating the images on each request. In this case, the call method needs to decide if a cache hit occurs and, if not, generate the thumbnail:
  # Main Rack call responder
def call(env)
if env['REQUEST_URI'] =~ /_sm.jpe?g/
# Handle thumbnail requests
unless File.exists?(filename(env))
mk_thumbnail(env)
end

small = File.new(filename(env)).read
[200, { }, small]
else
# Pass-thru non thumbnail requests
@app.call(env)
end
end
The rest of the code remains essentially the same. The complete, seemingly functional Rack handler:
class ThumbNail
# hard-code the store location (could be set via use options)
STORE = '/var/cache/thumbnail'

# Basic Rack initialization
def initialize(app); @app = app end

# Main Rack call responder
def call(env)
if env['REQUEST_URI'] =~ /_sm.jpe?g/
# Handle thumbnail requests
unless File.exists?(filename(env))
mk_thumbnail(env)
end

small = File.new(filename(env)).read
[200, { }, small]
else
# Pass-thru non thumbnail requests
@app.call(env)
end
end

# Make the thumbnail, storing it in the cache for subsequent
# requests
def mk_thumbnail(env)
$stderr.puts "[thumbnail] building thumbnail..."
cache_filename = filename(env)
path = cache_filename.sub(/\/[^\/]+$/, '')
FileUtils.mkdir_p(path)

env['REQUEST_URI'].sub!(/_sm\./, '.')
env['REQUEST_PATH'].sub!(/_sm\./, '.')
env['PATH_INFO'].sub!(/_sm\./, '.')

http_code, headers, body = @app.call(env)

img_data = ''
body.each do |data|
img_data << data
end

ImageScience.with_image_from_memory(img_data) do |img|
img.resize(200, 150) do |small|
small.save cache_filename
end
end
end

# Helper method for calculating the location of the file in the
# cache.
def filename(env)
"#{STORE}#{env['PATH_INFO']}"
end
end
Updating my Sinatra app to pull these images, I find the response time on my homepage much better (going from 1-2 seconds to ~100ms):



Tomorrow I delete all this code and then go back and do it right. Even in this limited spike, there is already code with which I am unhappy. A little BDD should clear that up.

Friday, March 6, 2009

Test CouchDB Database with Cucumber and Sinatra

‹prev | My Chain | next›

Continuing the chain, tonight I finish the spike of using Cucumber, Sinatra, and CouchDB together.

Thanks to a hint from Joseph Wilk, I already have a good idea how to work with a CouchDB test instance. Let's see if it pans out...

First I modify the spike.rb Sinatra code to use a different database by adding an environment-dependent db method:
require 'rubygems'
require 'sinatra'
require 'rest_client'
require 'json'

#####
# Use a different CouchDB instance in test mode
def db
Sinatra::Application.environment == :test ?
"http://localhost:5984/eee-test" :
"http://localhost:5984/eee-meals"
end

get '/meals/:permalink' do
data = RestClient.get "#{db}/#{params[:permalink]}"
result = JSON.parse(data)
%Q{
<h1>#{result['title']}</h1>
<p>We enjoyed this meal on #{result['date']}</p>
<p>#{result['summary']}</p>
<p>navigation and links to recipes would go here...</p>
<div>
#{result['description']}
</div>
}
end
A Before block (which is a Cucumber hook) can be added to create the test DB before each scenario (db is the method from the Sinatra app):
Before do
RestClient.put db, { }
end
Similarly, an After block can be used to tear down the DB after each scenario:
After do
RestClient.delete db
end
These blocks seem to work fine in the features/support/env.rb file, which is then:
# NOTE: This must come before the require 'webrat', otherwise
# sinatra will look in the wrong place for it's views.
require File.dirname(__FILE__) + '/../../spike'

# RSpec matchers
require 'spec/expectations'

# Webrat
require 'webrat'
Webrat.configure do |config|
config.mode = :sinatra
end

World do
session = Webrat::SinatraSession.new
session.extend(Webrat::Matchers)
session
end

Before do
RestClient.put db, { }
end

After do
RestClient.delete db
end
Lastly, I need to implement the Given step from yesterday's spike (see the discussion in the comments):
Given /^a "(.+)" meal$/ do |title|
@permalink = title.gsub(/\W/, '-')

RestClient.put "#{db}/#{@permalink}",
{ :title => title }.to_json,
:content_type => 'application/json'
end
If the Given text reads 'Given a "Breakfast Elves" meal', then the string "Breakfast Elves" will be assigned to the block's title variable. I use that to calculate a permalink (id) for the document by replacing all non-characters with a dash. RestClient puts the new document, with the appropriate title, into the DB.

By assigning the permalink to an instance variable, it is re-usable in subsequent steps, in this case the "When I view the meal permalink" step:
When /^I view the meal permalink$/ do
visit("/meals/#{@permalink}")
end
Thus, then entire steps file for my spike becomes:
Given /^a "(.+)" meal$/ do |title|
@permalink = title.gsub(/\W/, '-')

RestClient.put "#{db}/#{@permalink}",
{ :title => title }.to_json,
:content_type => 'application/json'
end

When /^I view the meal permalink$/ do
visit("/meals/#{@permalink}")
end

Then /^the title should include "(.+)"$/ do |title|
response.should have_selector("h1", :content => title)
end
Now when I run it, I get 3 passing steps without the oogy feeling about that empty Given:
Feature: See a meal

So that I can see an old meal
As a web user
I want to browse a single meal by permalink
Scenario: View Meal
Given a "Breakfast Elves" meal
When I view the meal permalink
Then the title should include "Breakfast Elves"


1 scenario
3 steps passed
All that is left is to rm -rf the spike code.

Some Final Thoughts

Creating and deleting the DB for each scenario is a coarse solution compared to using transactions to rollback test data in ActiveRecord tests. Even so, this just might be acceptable.

The scenario runs in under 0.5 seconds. That is about what the typical scenario takes in my experience with Rails.

It is not as if any structure needs to be built up in the CouchDB instance upon DB creation—that is one of the points of a document oriented database, after all.

I will have to ruminate on this, but reimplementing EEE Cooks on Sinatra might just work. Then again, it may prove hard to resist a Merb or Rails edge spike over the next couple of nights.

Wednesday, March 4, 2009

Spike Sinatra and CouchDB

‹prev | My Chain | next›

Continuing the chain, tonight I do a quick spike of running Sinatra on top of CouchDB.

Much of this is based on the work in http://ryanfunduk.com/fun-with-couchdb/.

My only goal here was to get a single meal displayed in a browser. Once I have that done, I'll continue this spike by trying out a little cucumber. Soo...

I had previously installed CouchDB. If memory serves, I used the command:
sudo apt-get install couchdb
I love Ubuntu.

With that, I navigated to futon at http://127.0.0.1:5984/_utils/ and create a new database:



Then I created a meal:



And added some attributes:



Just to be sure, I curl the record:
cstrom@jaynestown:~$ curl http://localhost:5984/eee-meals/2005-12-07-breakfast-elves
{
"_id": "2005-12-07-breakfast-elves",
"_rev": "571520480",
"title": "Breakfast Elves",
"date": "2005-12-07",
"summary": "Field trip bread inspires this post-St. Nicholas Day dinner. Our daughter
returned from her class field trip with a nice little loaf of brown bread.
There was not enough for our not-so-little family, so we also serve pancakes.",
"description": "<p> Yesterday was St. Nicholas Day—better known as Elves's Day
in our family. The kids dutifully placed their Christmas lists in their
stocking and awoke to find the lists replaced by candy and Christmas
ornaments. We hang the ornaments on the Christmas tree tonight.
</p> <p> The baby hurt her leg the other day. Robin was
helping our daughter with some school work when she heard a crash from the
other room. This, of course, is typical in our house, but we grew very
concerned when we realized that the baby could not stand. Happily, she
was inspired by the toys in the pet aisle at Wegmans to try walking
tonight. </p>"
}
With that I am ready to set up Sinatra and have it pull the meal from CouchDB. First up, install the json and sinatra gems:
gem install sinatra
gem install json
gem install rest-client


At that point, all that's needed is a little standing on the shoulders of giants. RestClient gets the data from CouchDB. JSON parses the data. Then, we render the HTML:
require 'rubygems'
require 'sinatra'
require 'rest_client'
require 'json'

DB = 'http://localhost:5984/eee-meals'

get '/meals/:permalink' do
data = RestClient.get "#{DB}/#{params[:permalink]}"
result = JSON.parse(data)
%Q{
<h1>#{result['title']}</h1>
<p>We enjoyed this meal on #{result['date']}</p>
<p>#{result['summary']}</p>
<p>navigation and links to recipes would go here...</p>
<div>
#{result['description']}
</div>
}
end
The resulting page is:



Not quite this, but it'll do for a spike.