blog

Yesterday was our first Sandy Spring CSA pickup of the year — we’ve got 24 more before we’re done, running through October 22nd. I don’t know that I’ll stick with doing this every week (Historical Record Magic 8-Ball sez: “HAHAHAHAHAHAHA”), but here’s what we got and what I’m planning on doing with it:

First, what was in the box, in no particular order:

  • 1 bunch baby scarlet turnips
  • 1 bunch red radishes
  • 2 bunches collard greens
  • 1 bunch scallions
  • 2 heads of lettuce (1 “butterhead”, 1 “green leaf”)
  • 1 bunch purple mizuna
  • 2 heads baby bok choy
  • 1 bunch of carrots

(There was another big head of bok choy in the box, but I swapped that for a second bunch of collard greens out of the Swap Box.)

Here’s my menu list for the next week, which manages to use everything except the greens from the carrots, radishes, and turnips (and even those will probably migrate into a salad mix at some point…)

  • Wednesday: lettuce salad with mushrooms, radishes, cherry tomatoes, grilled chicken, and balsamic vinaigrette
  • Thursday: collard green stew with chorizo and garlic
  • Friday: hamburgers, roasted turnip fries with Parmesan
  • Saturday: carnitas tacos con guacamole y pico de gallo (requested by @MrsGenehack for Mother’s Day…)
  • Sunday: bok choy / mizuna / tofu stir fry + cooking down chicken stock (this is where the carrots are headed)
  • Monday: lettuce salad with mushrooms, radishes, grilled steak, and balsamic vinaigrette (and maybe some additional greens)
  • Tuesday: mexi-melt chicken surprise

(Wikipedia has a nice CSA article if you’re all “WAT.”)

This morning, I was finishing off my coffee and reading the morning email -- as you do -- when I came across a bug report for Git::Wrapper, a module I maintain. It turned out that a recent change I'd made to my workflow (archiving older releases in my working tree) had resulted in the archived releases being included in the version of the software I'd packaged and put on CPAN for distribution.

Whoops! I needed to fix the problem and get a new release uploaded to CPAN as soon as possible, and since it was a quiet Saturday morning and I had about an hour free before I needed to run some errands for @MrsGenehack, I didn't expect it would be a big deal. I use Dist::Zilla to help me package up Git::Wrapper for distribution, so I figured it would just be a simple matter of tweaking the configuration in the dist.ini file in my working copy and then releasing a new version to CPAN. How long could it take, really?

(Enter First Yak, stage right, with bouffant rampant...)

I tried a couple of different approaches to changing the configuration so that it would do what I wanted, and couldn't quite get the syntax right. Instead of continuing to pound my head into a wall, I hopped onto the #distzilla channel on irc.perl.org and asked for help. RJBS (author of Dist::Zilla, current Perl pumpking, and generally nice guy) quickly pointed out where I was going wrong and got me on the right path.

I was working on the problem in a MultiTerm buffer in my editor, Emacs. I'm giving a talk on editor tweaks for more effective programming at YAPC::NA this year, and as part of prepping for that, I'm trying to do as much work as possible inside my editor. This was working great for this particular problem -- I could make changes to my dist.ini file and quickly jump over to the terminal window to run dzil commands and verify the distribution was getting built correctly.

This was working really well, except that I kept getting distracted by some highlighting irregularities -- and since the talk was on my mind, I realized I wasn't going to be able to present at YAPC with those ugly background glitches present. Obviously, taking a couple of minutes to clean that up would be time well spent...

(Enter Second Yak, stage left, somewhat hirsute than previous yak...)

Since most of the highlighting problems seemed to be around the color highlighting in the output of the ls command, I spent a while poking at the dircolors config file I use. I copied this from someplace on the Internets and I've never really taken the time to understand it -- it just worked -- so this was mostly poking of the "change something, see what happens" variety. After a few minutes of failing with this approach, I started to wonder if I was barking up the wrong tree. A bit of DuckDuckGo-ing later, I made a quick tweak to my Emacs config, which fixed the highlighting problem.

(Exit Second Yak, now smooth and free of hair)

That taken care of, I returned to the issue of the Git::Wrapper distribution problem. Before I got diverted by the Emacs shell issue, I'd noticed a few other things in the dist.ini file that I could improve. I took care of that, built a new release, and uploaded it to CPAN. I let the bug reporter know, and closed out the ticket.

(Exit First Yak, now also denuded.)

One of the changes I'd made to the dist.ini was updating the metadata to point to the new Git::Wrapper homepage and to the issue tracker for Git::Wrapper on Github. The MetaCPAN site uses this information to set up the links in the sidebar on the Git::Wrapper release page, so I hopped over there to verify that I'd done everything correctly.

All the links were working correctly, but a Github specific popup was appearing over my homepage link -- which seemed wrong. I jumped on the #metacpan channel to see if this had already been reported, and ended up having a short conversation with MST that resulted in me opening an issue ... which I ended up assigning to myself. (MST: manipulating people into open source contributions for fun and profit.)

(Enter Bonus Yak, descending from the rafters and bearing a strong similarity to MST, at least on the hairdo level... )

I looked at the issue briefly, but as I'd now used up about 1.5 hours of my free hour, I had to let it sit briefly while I took care of those errands. Once I got back, I spent another 30 minutes figuring out the issue. After I was sure I'd got it taken care of, I sent in a pull request, which has since been merged -- the bug is no longer visible on the MetaCPAN site).

(Exit Bonus Yak, freed of hair and looking not unlike MST would have if he hadn't backed out of the "transparent" option when losing the Iron Man Perl challenge...)

Anyway, that's my Saturday morning - three yaks shaved, 2 patches to open source projects, 1 editor config tweak, and some good raw material to fold into my talk. Hope you enjoyed the tale...

(For those of you wondering about the yak thing, "yak shaving" is a geeky way to describe what happens when you're trying to accomplish one thing, but get diverted off on solving a chain of seemingly unrelated problems instead.)

(Hat tip to Josh paperbits DiMauro for the title...)

I apologize for the lack of recent Jacquard entries — I had a few posts buffered up with the intent that I would be able to keep regularly posting even if I couldn’t maintain a regular rate of writing and developing — but then Skyrim came out, and my buffer got empty, and well, yeah. Here we are. I hope to pick up the project and the writing again now that the end-of-year/beginning-of-year madness has now mostly died down, so watch this space.

(ObSkyrim link: @SkyrimMom)

  • Like Girl Talk? Like dance? Just like cool shit? Go watch all the Girl Walk videos. Right now.
  • It’s okay, really. I’ll wait. Go watch that shit.
  • This is a really good article about the principle of mise en place. Lots of application to stuff beyond cooking. (And if you’re going “mise what?”, then you should certainly read it.)
  • Excellent, excellent inspiring videos from makers of things. If anybody is interested in giving me a very expensive gift, those knives look to be the shizzle. (Link via gphat.)
  • Future tattoo material.
  • Thanks to Gabor for the Jacquard shout out in the latest Perl Weekly. If you’re into Perl, you should subscribe to this newsletter, it’s a good roundup of Perl-related stuff from around the web.
  • MongoDB sucks. No, it doesn’t. (Former link from everywhere; latter from the comments over at Flutterby.)
  • Charlie Stross on Evil Social Networks. Quoted for Truth: “If you’re not paying for the product, you are the product.”
  • Be On Fire - “YOU. MUST. BURN.”

Since our previous installment got us users and authentication, we’re ready to start adding support for various services. One of the features of Jacquard — one of the main points of Jacquard, actually — is interacting with multiple services. To make that possible, we’ve included the accounts attribute in our User class:

# this attribute is going to contain info about all the services
# this user has configured -- i.e., there will be one for Twitter,
# one for Facebook, etc.
has accounts => (
  isa     => 'KiokuDB::Set',
  is      => 'ro',
  lazy    => 1 ,
  default => sub { set() },
);

Before we start actually writing the code for the things that are going to be inside those accounts attributes, it’s worth stepping back and thinking about what the data we want to store looks like, and how we can best structure our classes to help us manipulate that data.

Ideally, what we want — and again, this is a reflection of the underlying raison d’etre of Jacquard — is to be able to interact with all the different services we support in the same way without having to worry how each individual service handles fetching new posts, or writing a new post out. In other words, to be able to do something like this:

# warning: pseudocode
foreach my $account ( $self->accounts->members ) {
  $account->get_new_posts;
}

# or even
my $new_post = get_new_post_from_user();
foreach my $account ( $self->accounts->members ) {
  $account->post( $new_post )
}

Since we’re using Moose, we’re going to have a number of Jacquard::Schema::Account::FOO classes, one for each type of service we’re going to interact with. Each of those classes will consume an API-defining role (called something like Jacquard::Schema::Role::AccountAPI) that will define the required methods for the common interface we want all services to have — that is, making sure they support a get_new_posts method, and a post method, and so forth.

We also need to think about how to structure the other data associated with services. That data will fall into two broad categories: account information (and similar data, like authentication tokens, etc.) and posts on that service. Depending on the exact service, the details of what a ‘post’ is will differ — a tweet is not quite a FaceBook post, and both are very distinct from a blog post entry in an Atom feed — but they share enough commonalities that we can again take a similar approach: a number of Jacquard::Schema::Post::FOO classes, each consuming a Jacquard::Schema::Role::PostAPI role that ensures that they’re implementing a common API.

The benefit of this approach is that it becomes relatively trivial to add support for new services — particularly if there’s already a module on CPAN to handle interacting with that service. As we’ll see in a number of upcoming posts, taking an existing library and wrapping it in a layer of Moose class to implement a particular API is very little work.

I often find it helpful, when I’ve gotten to this point in the process of designing something and I think have a workable solution, to work out how a small set of data would map across instances of these classes. Let’s consider how a single Jacquard user, with a Twitter account configured within Jacquard, would look once a few tweets were stored:

# first, the user
my $user = Jacquard::Schema::User->new( name => 'Bob' );

# then we add the account
$user->add_account( 'Twitter' , %account_details );

# and then we get the most recent posts
$user->get_account( 'Twitter' )->get_new_posts();

And for this design, this is the point where I realize I haven’t really thought at all about how the individual Post objects will be associated with the Account object. The simplest way to do this would be for the Account classes to have a posts attribute, much like the accounts attribute in the User class:

has posts => (
  isa     => 'KiokuDB::Set',
  is      => 'ro',
  lazy    => 1 ,
  default => sub { set() },
);

Assuming that is how we go, after that get_new_posts() method above, we’d end up with the accounts attribute of $user containing a KiokuDB::Set object with a single member — an instance of Jacquard::Schema::Account::Twitter. Inside that object, there would be another KiokuDB::Set object with a bunch of members, each one an instance of Jacquard::Schema::Post::Twitter corresponding to an individual tweet from this user’s timeline (and having attributes like ‘author’, ‘content’, ‘datetime’, ‘id’, and so on).

That all seems to make a reasonable amount of sense — but there’s a looming problem. (If you’ve already spotted it, give yourself a pat on the back.) What happens when we add a second User, also with a Twitter account configured, and that user ends up following some of the same people on Twitter as our first user? We’ll end up with Post objects that are essentially duplicates of each other — but one copy will be inside the Twitter Account object of the first user, and the second will be inside the Twitter Account object of the second. In the long run, that’s going to end up being a big waste of storage space and/or RAM.

How do we solve this problem? We could just maintain a uniform set of Post objects, and include the same object into different Account objects as needed. That would solve the issue with the duplication of information — but it introduces another issue, in that we no longer have a place to store per-user metadata about individual Post objects (e.g., read/unread status).

Instead, we’ll solve this problem the old fashioned way: we’ll introduce another layer of abstraction! Instead of the posts attribute of Account objects containing Jacquard::Schema::Post objects directly, we’ll have a generic Jacquard::Schema::UserPost object that maps between a User account and a particular Post. In return for making our data model slightly more complicated, this approach gives us the best of both worlds, in that we have a place for per-User metadata to live, but the original Post data is only present in our system once, regardless of how many of our users have it present in their Account objects.

This solution also doesn’t impact any of our previous design decisions: the Jacquard::Schema::Role::PostAPI can be consumed by the Jacquard::Schema::UserPost class too, via method delegation to the Jacquard::Schema::Post::FOO object it refers to. (More about that later.)

So, now that we’ve been though a couple of rounds of thinking about the data structures, we can write some code, yes? Well, no, not exactly, not quite yet. Instead we’re going to explore what the API for using this code might look like, and we’re going to do that by writing some test code, or at least outlining some test cases.

First, we’re going to need to be able to add Account objects to User objects, and Post objects to Account objects. The code for that will probably look something like:

## method to associate an Account object with a User
# $model is an instance of Jacquard::Model::KiokuDB, 
# while $user is a Jacquard::Schema::User, 
# and $account->does('Jacquard::Schema::Role::AccountAPI')
$model->add_account_to_user( $account , $user );

## method to add a UserPost object to an Account -- will also save the
## associated Post object if needed 
# $model is an instance of Jacquard::Model::KiokuDB, 
# while $account->does('Jacquard::Schema::Role::AccountAPI')
# and $post->does('Jacquard::Schema::Role::PostAPI')
$model->add_post_to_account( $userpost , $account );

(Aside: I spent more time than I am willing to disclose trying to decide whether the order of arguments in those methods should be ‘more generic object, more specific object’, or if they should instead be the same as in the method name — which is what I finally went with, reasoning that will serve as a mnemonic.)

We’ll also need to be able to remove Account objects from User objects, and modify Post and UserPost objects and save those changes:

## method to remove an Account object from a user
# $model is an instance of Jacquard::Model::KiokuDB, 
# while $account->does('Jacquard::Schema::Role::AccountAPI')
# doesn't need a user object because $account has an 'owner' attribute
$model->remove_account_from_user( $account );

## method to store a modified Post or UserPost object, e.g. after
## changing some of the metadata, or if the underlying post object is
## updated
# $model is an instance of Jacquard::Model::KiokuDB, 
# while $post->does('Jacquard::Schema::Role::PostAPI')
$model->update_post( $post );

Those all look reasonable, at least at first glance. It’s worth noting that none of the methods have an explicit return value — they will just return true on success (and will likely eventually throw some sort of exception object on failure). This approach makes the most sense to me, as it is isolates the model to just marshaling objects to storage. Any modification or manipulation of the objects will happen elsewhere.

At this point, we’ve fleshed out the data model more, we have the beginnings of a plan for implementing the code that will let Jacquard interact with other services, and we have the outline for how we’re going to store and update that data in KiokuDB once we have it. That seems like a good place to stop. Next time, we’ll actually implement the first Account and Post classes!

As always, the code for Jacquard is available on Github. Patches are welcome; share and enjoy.

tired-soldiers.jpg

I started running some time in the late summer of 2010, doing the Couch To 5K program. I’d tried to start running a few other times, and I always had issues with shin splints that would prevent me from establishing any sort of routine. This had been the case for as long as I could remember — I ran track in my senior year of high school, and I had shin splint problems then too.

The thing that fixed those problems for me was this pair of Vibram Five Fingers KSOs. Running in these hurt at first too — but it was a different kind of hurt, a more manageable one, and one that got less the more I ran — the complete opposite of my shin splint problems, in other words.

My last run in these was the Marine Corps Marathon 10K. It was a cold, wet morning, and that hole you can see in the sole of the right shoe didn’t do me any favors — but I finished the race. Seemed like a good time to let these tired soldiers get some rest, so today I picked up a new pair of TrekSports. I’m hoping the slightly thicker sole and treads on the bottom will let me explore some trail running this spring — and who knows, there’s a local half marathon in May…

Those of you that aren’t familiar with the Vibrams, or the idea of minimalist running, may want to check out this NYT article for some background. I can’t say enough good things about these shoes; they’ve made it possible for me to run and enjoy it, and that’s just awesome.

In the last installment, we created Jacquard::Schema::User to describe a Jacquard user, and used Jacquand::Model::KiokuDB (and a helper script) to persist User objects to storage. This time around, we’re going to create our Catalyst app and hook up authentication.

So, first step: create the Catalyst application. The catalyst.pl helper makes this trivial:

$ catalyst.pl Jacquard::Web
created "Jacquard-Web"
created "Jacquard-Web/script"
created "Jacquard-Web/lib"
created "Jacquard-Web/root"
[ couple dozen more lines elided ]

Unfortunately, there’s no easy way to tell it “I’m creating this Cat app as a part of a bigger project” — so after creating it, you have to manually shuffle the files around to get them into the right place. The Catalyst files also come with quite a bit of templated stuff in them that we don’t need (POD skeletons and the like), so cleaning that up and getting the code into line with your personal coding style should be done at this point. Once that’s all done, checkpointing into revision control is a good idea:

$ git ci -m"Create Catalyst application" 
[03-catalyst 3c20771] Create Catalyst application
 11 files changed, 300 insertions(+), 0 deletions(-)
 create mode 100755 jacquard_web.psgi
 create mode 100644 lib/Jacquard/Web.pm
 create mode 100644 lib/Jacquard/Web/Controller/Root.pm
 create mode 100644 root/favicon.ico
 create mode 100644 root/static/images/btn_88x31_built.png
 create mode 100755 script/jacquard_web_cgi.pl
 create mode 100755 script/jacquard_web_create.pl
 create mode 100755 script/jacquard_web_fastcgi.pl
 create mode 100755 script/jacquard_web_server.pl
 create mode 100755 script/jacquard_web_test.pl

Next, we’re going to use CatalystX::SimpleLogin to add authentication to the application, following the outline in the manual. First up, add a number of plugins to the application (in lib/Jacquard/Web.pm):

use Catalyst qw/
    -Debug
    ConfigLoader
    +CatalystX::SimpleLogin
    Authentication
    Session
    Session::Store::File
    Session::State::Cookie
    Static::Simple
/;

Create a default View class by running:

./script/jacquard_web_create.pl view TT TT

Then create the Catalyst Model class that will wrap Jacquard::Model::KiokuDB:

package Jacquard::Web::Model::KiokuDB;
use Moose;

use Jacquard::Model::KiokuDB;

BEGIN { extends qw(Catalyst::Model::KiokuDB) }

has '+model_args'  => ( default => sub { { extra_args => { create => 1 }}});
has '+model_class' => ( default => 'Jacquard::Model::KiokuDB' );

__PACKAGE__->meta->make_immutable;
1;

We also need to add the configuration for these plugins to the application config file:

---
name: Jacquard::Web
Model::KiokuDB:
  dsn: dbi:SQLite:dbname=db/jacquard.db
Plugin::Authentication:
  default:
    credential:
      class: Password
      password_type: self_check
    store:
      class: Model::KiokuDB
      model_name: kiokudb

Finally, we can add a method requiring authentication to the root Controller (which is at lib/Jacquard/Web/Controller/Root.pm):

sub hello_user :Local :Does('NeedsLogin') {
  my( $self , $c ) = @_;

  my $name = $c->user->id;

  $c->response->body( "

Hello, $name!

" ); }

(Don’t forget that you need to change the parent class of the controller as well:

BEGIN { extends 'Catalyst::Controller::ActionRole' }

If things aren’t working, make sure you didn’t forget this.)

With all this in place, you should be able to start up the application, by either running ./script/jacquard_web_server.pl or, if you want to get all Plack-y and modern, plackup jacquard_web.psgi, and then browse to the URL the server reports it’s running on. You should see the Catalyst welcome page at that point. Add ‘/hello_user’ to the end of the URL, and you should get prompted for a username and password. Assuming you created an account using the helper script from the last installment, you should be able to give those same values and see a page that says ‘Hello’ and your test account username.

Now, are we done? Not quite, as we don’t have any tests of the authentication code! The following goes in t/lib/Test/Jacquard/Web/Controller/Root.pm:

package Test::Jacquard::Web::Controller::Root;
use parent 'Test::BASE';

use strict;
use warnings;

use Test::Most;
use Test::WWW::Mechanize::Catalyst;

sub fixtures :Tests(startup) {
  my $test = shift;

  # load test config
  $ENV{CATALYST_CONFIG_LOCAL_SUFFIX} = 'test';

  $test->{mech} = Test::WWW::Mechanize::Catalyst->new( catalyst_app => 'Jacquard::Web' );
}

sub auth_test :Tests() {
  my $test = shift;
  my $mech = $test->{mech};

  $mech->get_ok( '/' , 'basic request works' );
  is( $mech->uri->path , '/' , 'at top page' );

  $mech->get_ok( '/hello_user' , 'request hello_user' );
  is( $mech->uri->path , '/login' , 'redirect to login' );

  $mech->submit_form_ok({
    form_id => 'login_form' ,
    fields  => {
      username => 'test_user' ,
      password => 'test_password' ,
    } ,
    button => 'submit' ,
  } , 'login' );

  is( $mech->uri->path , '/hello_user' , 'redirect to /hello_user' );
  $mech->text_contains( 'Hello, test_user!' , 'see expected greeting' );

  $mech->get_ok( '/' , 'basic request works' );
  is( $mech->uri->path , '/' , 'at home page' );

  $mech->get_ok( '/hello_user' , 'request hello_user' );
  is( $mech->uri->path , '/hello_user' , 'go directly to hello_user' );
  $mech->text_contains( 'Hello, test_user!' , 'still see expected greeting' );

  $mech->get_ok( '/logout' );
  is( $mech->uri->path , '/' , 'back at home page' );

  $mech->get_ok( '/hello_user' , 'request hello_user' );
  is( $mech->uri->path , '/login' , 'redirect to login' );
}


1;

If you’re not familiar with Test::Class-style testing, you should review the links I gave in the post on the Jacquard project infrastructure. Even if you’re not that versed in Test::Class, hopefully the sequence above is fairly self-explanatory: we try to access a restricted URL, verify we get bounced to the login URL, then fill out and submit the login form, and verify we get re-directed to the original request. Following that, we logout and verify that we’re once again unable to get to the restricted resource. Fairly simple.

In order to make this work, we need a distinct application config for testing, one that defines a test user and password for us. Catalyst, of course, provides a way to do this — that’s what that line that sets the CATALYST_CONFIG_LOCAL_SUFFIX environment variable is about. The testing config goes into jacquard_test.yaml, and looks like this:

---
Plugin::Authentication:
  default:
    credential:
      class: Password
      password_field: password
      password_type: clear
    store:
      class: Minimal
      users:
        test_user:
          password: 'test_password'

With that test file and test config in place, we can run the tests:

$ prove -l -I./t/lib ./t/lib/Test/Jacquard/Web/Controller/Root.pm -v
./t/lib/Test/Jacquard/Web/Controller/Root.pm .. # 
# Test::Jacquard::Web::Controller::Root->auth_test

ok 1 - basic request works
ok 2 - at top page
ok 3 - request hello_user
ok 4 - redirect to login
ok 5 - login
ok 6 - redirect to /hello_user
ok 7 - see expected greeting
ok 8 - basic request works
ok 9 - at home page
ok 10 - request hello_user
ok 11 - go directly to hello_user
ok 12 - still see expected greeting
ok 13 - GET /logout
ok 14 - back at home page
ok 15 - request hello_user
ok 16 - redirect to login
1..16
ok
All tests successful.
Files=1, Tests=16,  4 wallclock secs ( 0.04 usr  0.00 sys +  3.67 cusr  0.20 csys =  3.91 CPU)
Result: PASS

and verify they pass. This is also a good point to rerun the whole test suite:

$ prove -l
t/01-run.t .. ok    
All tests successful.
Files=1, Tests=26,  6 wallclock secs ( 0.03 usr  0.01 sys +  4.16 cusr  0.27 csys =  4.47 CPU)
Result: PASS

So, at this point, we have a basic data model (which only models users — but that’s about to change!), a KiokuDB-based persistence framework, and we’ve got all that hooked into a Catalyst-based web application and can use the info in our User object to authenticate to the web app. Sounds like a good place to take a break! In our next installment, we’ll pull back from the coding just a bit and think about the best way to structure the data involved in the services we’re going to connect to, and the posts we’re going to read and write to those connections.

As always, the code for Jacquard is available on Github. Patches are welcome; share and enjoy.

Update: The Jacquard story continues with “Extending The Data Model”.

Okay, we’ve got our tooling support built up so we can easily and quickly run tests — time to do some Real Work!

Before any coding, it’s usually helpful to think about what we’re trying to do, and how best to break down the data involved in the problem. Since the point of Jacquard is to aggregate together multiple social networking sites (and RSS feeds, eventually), we’re going to have a few generic object types in the system: we’ll have User objects representing our users, Service objects representing the different types of social networks, Account objects that map between a Service and a particular User, and Post objects that represent the individual pieces of content on a particular service.

Given that breakdown of the data structures, one plan of attack is to first create the User class, get the basics of that working in the data model layer of the application, then hook it into the web application layer. Generally speaking, I find that getting to the point where I can log in to the web application is a good stopping point.

N.b. : I’m going to be borrowing very heavily from Nothingmuch’s intro to using KiokuDB in Catalyst applications post here — you may want to jump over and read that before continuing.

So, the first thing to create is our user class in our data model. Following the conventions discussed in Nothingmuch’s article, we’ll call this class ‘Jacquard::Schema::User’:

package Jacquard::Schema::User;
# ABSTRACT: Jacquard users
use Moose;
with qw/ KiokuX::User /;  # provides 'id' and 'password' attributes

# we're going to use this to map 'username' to the 'id' attr
use MooseX::Aliases;

# and this is an easy way to verify we're getting a valid email
use MooseX::Types::Email qw/ EmailAddress /;
 # these are a couple of helper classes that make Kioku easier to use
use KiokuDB::Set;
use KiokuDB::Util              qw/ set /;

use namespace::autoclean;

# we want to have our username be our unique ID in Kioku
alias username => 'id';

has email => (
  isa      => EmailAddress ,
  is       => 'ro' ,
  required => 1 ,
);

# this attribute is going to contain info about all the services
# this user has configured -- i.e., there will be one for Twitter,
# one for Facebook, etc.
has accounts => (
  isa     => 'KiokuDB::Set',
  is      => 'ro',
  lazy    => 1 ,
  default => sub { set() },
);

__PACKAGE__->meta->make_immutable;    
1;

To sanity check the basics that we’ve done so far, let’s make a simple test class for Jacquard::Schema::User — something like this:

package Test::Jacquard::Schema::User;
use strict;
use warnings;

use parent 'Test::BASE';

use Test::Most;

use KiokuX::User::Util qw/ crypt_password /;

use Jacquard::Schema::User;

sub test_constructor :Tests(7) {
  my $test = shift;

  my $user = Jacquard::Schema::User->new(
    id       => 'user1' ,
    email    => 'user1@example.com' ,
    password => crypt_password( 'bad_password' ) ,
  );

  isa_ok( $user , 'Jacquard::Schema::User' );

  is( $user->id       , 'user1'             , 'id' );
  is( $user->username , 'user1'             , 'name delegated to id' );
  is( $user->email    , 'user1@example.com' , 'email' );

  ok( $user->check_password( 'bad_password' ) , 'check password' );
  ok( ! $user->check_password( 'wrong password' ), 'check wrong password' );

  is_deeply( [ $user->accounts->members ] , [] , 'no accounts' );

}

What happens when we run that?

$ prove -lv
t/01-run.t .. # 
# Test::Jacquard::Schema::User->test_constructor

1..7
ok 1 - The object isa Jacquard::Schema::User
ok 2 - id
ok 3 - name delegated to id
ok 4 - email
ok 5 - check password
ok 6 - check wrong password
ok 7 - no accounts
ok
All tests successful.
Files=1, Tests=7,  1 wallclock secs ( 0.02 usr  0.01 sys +  0.53 cusr  0.03 csys =  0.59 CPU)
Result: PASS

It’s important to note at this point that we don’t have anything really KiokuDB-specific going on with that User class. Yes, we used a few Kioku-related helper classes, but that’s just because we knew we were headed towards KiokuDB eventually. Those helpers could easily be replaced (or even removed, in a few cases), leaving behind a simple Moose class that describes a User object. In order to really hook this up to KiokuDB, the next step is make a Model class. This will allow our data objects to persist (i.e., save them to disk), and also provides a place to put helper methods to wrap transactions and a way to define a data storage API that will be used by the Catalyst web application layer. (Cooler people might call this a data storage DSL…) Here’s an initial version of this Model class:

package Jacquard::Model::KiokuDB;
# ABSTRACT: KiokuX::Model wrapper for Jacquard
use Moose;
extends qw/ KiokuX::Model /;

sub insert_user {
  my( $self , $user ) = @_;

  my $id = $self->txn_do(sub {
      $self->store( $user )
  });

  return $id;
}

__PACKAGE__->meta->make_immutable;
1;

And of course, we need a test class too — this one uses Kioku’s ability to “store” things to memory, rather than a database, making it easier to set up the tests.

package Test::Jacquard::Model::KiokuDB;
use parent 'Test::BASE';

use strict;
use warnings;

use Test::Most;

use Jacquard::Model::KiokuDB;
use Jacquard::Schema::User;

use KiokuX::User::Util qw/ crypt_password /;

sub fixtures :Tests(startup) {
  my $test = shift;

  $test->{model} = Jacquard::Model::KiokuDB->new( dsn => 'hash' );
}

sub test_insert_user :Tests(3) {
  my $test = shift;
  my $m    = $test->{model};

  {
    my $s = $m->new_scope;

    my $id = $m->insert_user(
      Jacquard::Schema::User->new(
        id       => 'user1' ,
        email    => 'user1@example.com' ,
        password => crypt_password( 'bad_password' ) ,
      ),
    );

    ok( $id , 'got id' );

    my $user = $m->lookup( $id );

    isa_ok( $user , 'Jacquard::Schema::User' , 'looked up user' );
    is( $user->username , 'user1' , 'expected name' );
  }
}

1;

(Note how we’re using the Tests(startup) method attribute to set up our test fixtures.)

Running the test suite shows us that everything is working as we expect:

$ prove -lv
t/01-run.t .. # 
# Test::Jacquard::Model::KiokuDB->test_insert_user

ok 1 - got id
ok 2 - looked up user isa Jacquard::Schema::User
ok 3 - expected name
# 
# Test::Jacquard::Schema::User->test_constructor
ok 4 - The object isa Jacquard::Schema::User
ok 5 - id
ok 6 - name delegated to id
ok 7 - email
ok 8 - check password
ok 9 - check wrong password
ok 10 - no accounts
1..10
ok
All tests successful.
Files=1, Tests=10,  2 wallclock secs ( 0.03 usr  0.01 sys +  1.19 cusr  0.06 csys =  1.29 CPU)
Result: PASS

We’re almost ready to create our Catalyst application and hook up the authentication bits to our model/schema code — but first, let’s write a little helper utility to create a user. That will make our interactive testing of the web application a little bit easier. We’ll use SQLite and the KiokuDB/DBIx::Class bridge for the moment; if and when this gets rolled out to more people, we’d want to change that up to something with a bit more power (e.g., by swapping Postgres in for SQLite, or, if we want to hop the NoSQL train, by switching over to CouchDB).

First, a configuration file, so we don’t have to hardcode the database connection details. This goes in jacquard.yaml:

---
Model::KiokuDB:
  dsn: dbi:SQLite:dbname=db/jacquard.db

(Down the road, we’ll add the Catalyst application configuration to this file too.)

Next up, the helper script. This just needs to load up the config, prompt for needed info, create a Jacquard::Schema::User object, instantiate a KiokuDB connection with Jacquard::Model::KiokuDB, and use the insert_user method to store the object in the database. This will live in script/create_user:

#! /opt/perl/bin/perl

use strict;
use warnings;
use 5.010;

use FindBin;
use lib "$FindBin::Bin/../lib";

use Jacquard::Model::KiokuDB;
use Jacquard::Schema::User;
use KiokuX::User::Util         qw/ crypt_password /;
use YAML                       qw/ LoadFile       /;

my $dsn = parse_config_file();

my( $username , $email , $password ) = prompt_for_info();

my $user = Jacquard::Schema::User->new(
  username => $username ,
  email    => $email ,
  password => crypt_password( $password ),
);

my $m = Jacquard::Model::KiokuDB->connect( $dsn , create => 1 );
{
  my $s = $m->new_scope;

  my $id = $m->insert_user( $user );

  say "STORED USER ID '$id'";
}

# config file parsing and info prompting details elided; if you're
# really interested, the code is on Github... 

If we wanted to get really fancy, we could make this take command line flags for the needed information — and it should probably not echo the password back to the screen, and should handle the exception that’s going to be thrown if the email address isn’t properly formed, or if the username already exists — but that can all be added down the road. For the moment, we just need to get a User object saved in the database so we have something to authenticate against…

So, we run this to create a test user:

 $ ./script/create-user 
USERNAME? test
EMAIL? test@example.com
PASSWORD? bad
STORED USER ID 'user:test'

At this point, if you’re doing this for real, it’s worth pausing for a few minutes and using the SQLite tool to poke around inside the database that’s been created for you in db/jaquard.db. Since this is already a super long post and one of the overarching points of this series is that KiokuDB means you don’t need to worry about how your stuff lives on disk, we’re gonna skip that.

Next time, we’ll set up our Catalyst app and use this user class to hook up authentication.

Update: See the Catalyst application set up in “Setting Up Authentication”.