Skip to content

Make code more async #9

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"bluebird": "^3.4.6"
},
"devDependencies": {
"aws-sdk": "^2.1.29",
"aws-sdk": "^2.3.0",
"babel-cli": "^6.16.0",
"babel-preset-es2015-node4": "^2.1.0",
"babel-preset-es2017": "^6.16.0"
Expand Down
19 changes: 11 additions & 8 deletions src/exec.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,23 @@
import { exec } from 'child_process';

/**
* @return {Promise}
*/
export default function (...args) {
return new Promise((fulfill, reject) => {
return new Promise((resolve, reject) => {
console.log('executing', args[0])
exec(...args, (err, stdout, stderr) => {
exec(...args, (error, stdout, stderr) => {
console.log('execution finished');
console.log(`err \t${err}`);
console.log(`error \t${error}`);
console.log(`stdout\t${stdout}`);
console.log(`stderr\t${stderr}`);

if (err) {
err.stderr = stderr;
return reject(err);
if (error) {
error.stderr = stderr;
reject(error);
} else {
resolve({ stdout, stderr });
}

fulfill({ stdout, stderr });
});
})
}
89 changes: 44 additions & 45 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import AWS from 'aws-sdk';
import { promisifyAll } from 'bluebird';
import Promise, { promisifyAll } from 'bluebird';
import exec from './exec';

startTimer('init');
console.time('init');

const fs = promisifyAll(require('fs'));
const s3 = promisifyAll(new AWS.S3());

AWS.config.setPromisesDependency(Promise);
const s3 = new AWS.S3();

const BUCKET = 'lilybin-scores';
const LY_DIR = `${process.env.LAMBDA_TASK_ROOT}/ly`;
const mime = {
Expand All @@ -15,18 +18,11 @@ const mime = {
};

process.chdir('/tmp');

process.env.PATH += `:${LY_DIR}/usr/bin`;
process.env.LD_LIBRARY_PATH = `${LY_DIR}/usr/lib`;

function noop () {}

// Make sure this declaration is hoisted
var curTimer = null;
function startTimer(label) {
if (curTimer) console.timeEnd(curTimer);
if (label) console.time(label);
curTimer = label;
}
console.timeEnd('init');

function generateId() {
return [
Expand All @@ -40,53 +36,56 @@ function runLilypond() {
return exec(`lilypond --formats=pdf --include="${__dirname}/fonts/font-stylesheets" -o rendered input.ly >&2`);
}

async function uploadFile(id, file, mode) {
try {
await s3.putObjectAsync({
function uploadFile(id, file, mode) {
return fs.readFileAsync(file).then(body_ =>
s3.putObject({
Bucket: BUCKET,
Key: id,
Body: await fs.readFileAsync(file),
Body: body_,
ContentType: mime[mode],
StorageClass: 'REDUCED_REDUNDANCY'
});
return true;
} catch (err) {
return false;
}
}).promise()
).thenReturn(true).catchReturn(false);
}

async function uploadFiles(id, result) {
result.files = {
pdf: await uploadFile(`${id}.pdf`, 'rendered.pdf', 'pdf'),
midi: await uploadFile(`${id}.midi`, 'rendered.midi', 'midi')
};

return result;
function uploadFiles(result) {
return Promise.all([
uploadFile(`${result.id}.pdf`, 'rendered.pdf', 'pdf'),
uploadFile(`${result.id}.midi`, 'rendered.midi', 'midi')
]).spread((pdf_, midi_) => {
result.files = {
pdf: pdf_,
midi: midi_
};
return result;
});
}

async function run(event) {
function run(event) {
console.log('Received event:', JSON.stringify(event, null, 2));
const id = event.id || generateId();

startTimer('writing input');
await Promise.all([
fs.writeFileAsync('input.ly', event.code),
fs.unlinkAsync('rendered.pdf').catch(noop),
fs.unlinkAsync('rendered.midi').catch(noop)
]);

startTimer('lilypond');
let result = await runLilypond();
result.id = id;
console.time('writing input');

startTimer('upload');
result = await uploadFiles(id, result);

startTimer(null);
return result;
return Promise.all([
fs.writeFileAsync('input.ly', event.code),
fs.unlinkAsync('rendered.pdf').catchReturn(null),
fs.unlinkAsync('rendered.midi').catchReturn(null)
]).tap(() => {
console.timeEnd('writing input');
console.time('lilypond');
}).return(
runLilypond()
).then(result => {
result.id = id;
return result;
}).tap(() => {
console.timeEnd('lilypond');
console.time('upload');
}).then(uploadFiles).tap(() => console.timeEnd('upload'));
}

exports.handler = function (event, context, callback) {
exports.handler = (event, context, callback) => {
run(event)
.then(res => callback(null, res))
.catch(err => {
Expand Down