blog

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”.

Okay, first step is to get some tooling in place to make it easier to deal with developing this thing. Since I'm expecting to work on this for a while, and will probably end releasing the code on CPAN, it makes sense to invest a little up front effort on making testing and releasing the code easier.

Item the first: a Dist::Zilla config. If you're not familiar with Dist::Zilla, it's a set of tools to make it easier to write Perl code with an eye towards distributing it on CPAN. There's more info at the Dist::Zilla site.

Since I've been using dzil for a while, I've taken the step of uploading my own plugin bundle to CPAN -- so my dist.ini file to configure Dist::Zilla is pretty straightforward:

name    = Jacquard
author  = John SJ Anderson <genehack@genehack.org>
license = Perl_5
copyright_holder = John SJ Anderson <genehack@genehack.org>
copyright_year   = 2011

[@GENEHACK]

The intro boilerplate is pretty self-explanatory, and all that last line says is "use my standard plugins and settings."

Item the second: Test::Class tooling. I've been using the OO-ish approach to writing tests for a while now and I find it very convenient. I'm not going to try to explain how it works, since Ovid has already written a very nice series of articles over on Modern Perl Books about using this module:

To make it easier to use we're just going to create a test helper to run all our Test::Class tests -- this will go in a file called t/01-run.t:

#! perl
use strict;
use warnings;
use Test::Class::Load qw( t/lib );

All that does is automatically find all our testing libraries under t/lib and automatically run each one in turn. We're also going to create a testing base class at t/lib/Test/BASE.pm that all our test libraries will inherit from:

package Test::BASE;
use parent 'Test::Class';

INIT { Test::Class->runtests }

1;

This is done so that individual test libraries will do the right thing when run with the prove tool -- more about that in a later installment.

Item the third: a top level library file. This isn't strictly needed, and isn't going to contain any code, but I always like to have a module file that matches the name of the distribution. So we'll put this into lib/Jacquard.pm:

package Jacquard;
# ABSTRACT: Jacquard is a social network and RSS feed aggregator.
1;

At some point, we'll come back and revise that abstract line, once we have a better idea of what this thing wants to do.

For the moment, let's make sure things are "working" as expected:

<Jacquard:/> $ dzil test
[DZ] building test distribution under .build/EkNRq3jF7V
[DZ] beginning to build Jacquard
[DZ] guessing dist's main_module is lib/Jacquard.pm
[DZ] extracting distribution abstract from lib/Jacquard.pm
[@GENEHACK/@Basic/ExtraTests] rewriting release test xt/release/pod-coverage.t
[@GENEHACK/@Basic/ExtraTests] rewriting release test xt/release/pod-syntax.t
[@GENEHACK/@Basic/ExtraTests] rewriting release test xt/release/eol.t
[@GENEHACK/@Basic/ExtraTests] rewriting release test xt/release/kwalitee.t
[DZ] Override README from [ReadmeFromPod]
[DZ] writing Jacquard in .build/EkNRq3jF7V
Checking if your kit is complete...
Looks good
Writing Makefile for Jacquard
Writing MYMETA.yml and MYMETA.json
cp lib/Jacquard.pm blib/lib/Jacquard.pm
Manifying blib/man3/Jacquard.3
PERL_DL_NONLAZY=1 /opt/perl-5.14.2/bin/perl "-MExtUtils::Command::MM" "-e" "test_harness(0, 'blib/li    b', 'blib/arch')" t/*.t
t/00-compile.t ............ ok   
t/01-run.t ................ No subtests run 
t/release-eol.t ........... skipped: these tests are for release candidate testing
t/release-kwalitee.t ...... skipped: these tests are for release candidate testing
t/release-pod-coverage.t .. skipped: these tests are for release candidate testing
t/release-pod-syntax.t .... skipped: these tests are for release candidate testing

Test Summary Report
-------------------
t/01-run.t              (Wstat: 0 Tests: 0 Failed: 0)
  Parse errors: No plan found in TAP output
Files=6, Tests=1,  0 wallclock secs ( 0.04 usr  0.02 sys +  0.17 cusr  0.03 csys =  0.26 CPU)
Result: FAIL
Failed 1/6 test programs. 0/1 subtests failed.
make: *** [test_dynamic] Error 255
error running make test

And since we haven't actually written any tests yet, that's about what we should expect. That's a nice place to stop and commit what we've done so far:

[master]<Jacquard:/> $ git add dist.ini t/01-run.t t/lib/Test/BASE.pm lib/Jacquard.pm

[master 6cd7634] Set up basic dist.init, Test::Class tooling, and lib/Jacquard.pm
 4 files changed, 132 insertions(+), 0 deletions(-)
 create mode 100644 dist.ini
 create mode 100644 lib/Jacquard.pm
 create mode 100755 t/01-run.t
 create mode 100644 t/lib/Test/BASE.pm

and a good time to stop for the moment. In the next installment, we'll write some code that actually does something, and start figuring out how this thing is actually going to work.

Update: The Jacquard story continues in "Setting Up Users".

Around the beginning of 2010, I started a project that I eventually ended up calling App::StatusSkein. The idea was to provide reading and posting access to a variety of social networks from a single unified location. As these personal projects will, it grew to the point where it was tolerable for my primary use for it, and my desire to develop it further slackened. I had placed some (in retrospect) odd design constraints on it — I was trying to not have a backing database at all, to only run locally, and to only keep a certain minimal amount of state loaded at any given time. After the initial page load, all the interaction between the web browser and the server was AJAX-based, and reloading the page would reset the state to the initial default. Parts of this worked well; parts of it… just worked, but all in all, it was successful at scratching the itch I had at the time.

Now, I’ve got a different itch — same general area, but different design constraints. Now that I’ve got an iPad, it would be nice to have something similar to StatusSkein, but server-based, able to keep track of where in the timeline I’d last left off reading, able to save posts for later, and able to track precisely which posts I’ve read and which I haven’t, regardless of what location I accessed them from — something like a mashup of the UI of Google Reader and the current StatusSkein. Technology-wise, I’d also like a chance to play around with a Catalyst app that uses KiokuDB instead of the usual (for me) DBIx::Class. It would also be nice if I had a better way of maintaining my interest in the development of this app beyond the initial “hey, this itches!” stage. The ideal way to do that is to get users. Failing that, perhaps readers will provide some motivation…

So, welcome to what is hopefully the first in a series of posts outlining bite-sized bits of coding and other noddling around as I work on developing this new trans-social network app that I’m currently calling Jacquard

Update: The Jacquard story begins in “Setting Up Project Infrastructure”.