Skip to content
Merged
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
3 changes: 3 additions & 0 deletions docs/adapters/file.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,9 @@ write file -file <path>
Parameter | Description | Required?
----------------- | -------------------------------- | ---------:
`-file` | File path on the local filesystem, absolute or relative to the current working directory | Yes
`-bufferLimit` | Maximum number of points to buffer in memory before each write to the specified file | No; defaults to 100000
`-maxFilesize` | Maximum size of the file being written to, limited since the entire JSON needs to fit in memory | No; defaults to 200MB
`-flushFrequency` | How often (in number of points) to flush the points in memory out to the specified file | No; defaults to every 100 points

If the file already exists and contains a valid JSON array, the write will append new data rather than overwrite.

Expand Down
18 changes: 18 additions & 0 deletions lib/adapters/file/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
//
// Simple Juttle adapter that implements a single file "database".
//
// The "file" option indicates a file to read/write from and it must contain
// a JSON array of objects.
//
// The filters passed in the read parameterrs are executed to filter the points
// from the file.

function FileAdapter(config, Juttle) {
return {
name: 'file',
read: require('./read'),
write: require('./write')
};
}

module.exports = FileAdapter;
84 changes: 6 additions & 78 deletions lib/adapters/file-adapter.js → lib/adapters/file/read.js
Original file line number Diff line number Diff line change
@@ -1,20 +1,9 @@
//
// Simple Juttle adapter that implements a single file "database".
//
// The "filename" option indicates a file to read/write from and it must contain
// a JSON array of objects.
//
// The filters passed in the read parameterrs are executed to filter the points
// from the file.

/* jshint evil: true */

var _ = require('underscore');
var Juttle = require('../runtime/index').Juttle;
var JuttleMoment = require('../moment').JuttleMoment;
var parsers = require('./parsers');
var fs = require('fs');
var values = require('../runtime/values');
var Juttle = require('../../runtime/index').Juttle;
var JuttleMoment = require('../../moment').JuttleMoment;
var parsers = require('../parsers');
var values = require('../../runtime/values');

var Read = Juttle.proc.source.extend({
sourceType: 'batch',
Expand Down Expand Up @@ -49,7 +38,7 @@ var Read = Juttle.proc.source.extend({
});
}

this.to = options.to || this.program.now;
this.to = options.to || new JuttleMoment(Number.POSITIVE_INFINITY);
if (!this.to.moment) {
throw this.compile_error('RT-FROM-TO-MOMENT-ERROR', {
value: values.inspect(this.to)
Expand Down Expand Up @@ -100,66 +89,5 @@ var Read = Juttle.proc.source.extend({
}
});

var Write = Juttle.proc.sink.extend({
procName: 'write-file',
initialize: function(options, params) {
var allowed_options = ['file'];
var unknown = _.difference(_.keys(options), allowed_options);
if (unknown.length > 0) {
throw this.compile_error('RT-UNKNOWN-OPTION-ERROR', {
proc: 'write file',
option: unknown[0]
});
}

if (!_.has(options, 'file')) {
throw this.compile_error('RT-MISSING-OPTION-ERROR', {
proc: 'write file',
option: "file"
});
}

this.filename = options.file;
this.queue = [];
},

process: function(points) {
this.logger.debug('process', points);
this.queue = this.queue.concat(points);
},

flush: function() {
// XXX/demmer this should be asynchronous
var data;
var points = [];
try {
data = fs.readFileSync(this.filename, 'utf8');
points = JSON.parse(data);
} catch (err) {
if (err.code !== 'ENOENT') {
this.logger.error('error reading file:', err.toString());
}
}
points = points.concat(this.queue);
data = JSON.stringify(points, null, 4);
fs.writeFileSync(this.filename, data);

this.queue = [];
},

eof: function() {
this.logger.debug('eof');
this.flush();
this.done();
}
});

function FileAdapter(config) {
return {
name: 'file',
read: Read,
write: Write
};
}

module.exports = FileAdapter;
module.exports = Read;
143 changes: 143 additions & 0 deletions lib/adapters/file/write.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
var _ = require('underscore');
var Juttle = require('../../runtime/index').Juttle;
var Promise = require('bluebird');
var fs = Promise.promisifyAll(require('fs'));

var Write = Juttle.proc.sink.extend({
procName: 'write-file',
initialize: function(options, params) {
var allowed_options = ['file', 'bufferLimit', 'maxFilesize', 'flushFrequency'];
var unknown = _.difference(_.keys(options), allowed_options);
if (unknown.length > 0) {
throw this.compile_error('RT-UNKNOWN-OPTION-ERROR', {
proc: 'write file',
option: unknown[0]
});
}

if (!_.has(options, 'file')) {
throw this.compile_error('RT-MISSING-OPTION-ERROR', {
proc: 'write file',
option: "file"
});
}

this.bufferLimit = options.bufferLimit || 100000;
if (!_.isNumber(this.bufferLimit) || this.bufferLimit < 0 ) {
throw this.compile_error('RT-OPTION-SHOULD-BE-POSITIVE-INTEGER', {
option: "bufferLimit"
});
}

// 200MB bufferLimit on file
this.maxFilesize = options.maxFilesize || 200*1024*1024;
if (!_.isNumber(this.maxFilesize) || this.maxFilesize < 0 ) {
throw this.compile_error('RT-OPTION-SHOULD-BE-POSITIVE-INTEGER', {
option: "maxFilesize"
});
}

// flush every 100 points
this.flushFrequency = options.flushFrequency ? options.flushFrequency : 100;
if (!_.isNumber(this.flushFrequency) || this.flushFrequency < 0 ) {
throw this.compile_error('RT-OPTION-SHOULD-BE-POSITIVE-INTEGER', {
option: "flushFrequency"
});
}

this.filename = options.file;
this.queue = [];
},

process: function(points) {
this.logger.debug('process', points);
this.queue = this.queue.concat(points);
// if we're due for a flush and don't have a flush in course then
// fire off another flush
if (this.queue.length > this.flushFrequency && !this.flushPromise) {
this.flush();
}
},

flush: function() {
var self = this;
var points = [];

this.flushPromise = fs.statAsync(this.filename)
.then(function(stats) {
if (stats.size > self.maxFilesize) {
throw self.runtime_error('RT-OPTION-VALUE-EXCEEDED', {
option: 'maxFilesize',
value: self.maxFilesize + ' bytes'
});
}
// we can only read the file if it exists which would be here
// and only after verifying the maxFileSize has not been
// exceeded
return fs.readFileAsync(self.filename, 'utf8')
.then(function(data) {
points = JSON.parse(data);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A thing to keep in mind (we don't have to fix it now) is that this introduces a potential race condition - other file sink / other process could do a write while we keep the points in memory, and we'd then overwrite that write's content.

});
})
.catch(function(err) {
// ignore the ENOENT since that means we don't have an output
// file to begin with
if (err.code !== 'ENOENT') {
throw err;
}
})
.then(function() {
if (points.length > self.bufferLimit) {
self.trigger('error', self.runtime_error('RT-OPTION-VALUE-EXCEEDED', {
option: 'bufferLimit',
value: self.bufferLimit,
extra: ', droppping points.'
}));
return Promise.resolve();
} else {
var space_left = self.bufferLimit - points.length;
if (space_left < self.queue.length) {
points = points.concat(self.queue.slice(0, space_left));
// error since we really can't take any more points after this and
// should stop the whole pipeline
self.trigger('error', self.runtime_error('RT-OPTION-VALUE-EXCEEDED', {
option: 'bufferLimit',
value: self.bufferLimit,
extra: ', droppping points.'
}));
} else {
// lets write out some more points
points = points.concat(self.queue);
}
var data = JSON.stringify(points, null, 4);
self.queue = [];
return fs.writeFileAsync(self.filename, data);
}
})
.catch(function(err) {
self.trigger('error', err);
}).finally(function() {
self.flushPromise = null;
});

return this.flushPromise;
},

eof: function() {
this.logger.debug('eof');
var self = this;
var currentFlush = this.flushPromise || Promise.resolve();
currentFlush.then(function() {
// after the current flush is done lets make sure to fire off
// another one as the previous one could have been somewhere
// in the middle of the async write and without another flush we
// would leave points on the self.queue
return self.flush();
})
.then(function() {
self.done();
});
}
});

module.exports = Write;
2 changes: 1 addition & 1 deletion lib/adapters/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
var Juttle = require('../runtime/index').Juttle;

var stochastic = require('./stochastic-adapter');
var file = require('./file-adapter');
var file = require('./file');
var http = require('./http');

// register the built-in adapters
Expand Down
2 changes: 1 addition & 1 deletion lib/adapters/parsers/csv.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ module.exports = base.extend({
});

csvStream.on('error', function(err) {
reject(errors.compileError('RT-INVALID-CSV-ERROR',{
reject(errors.runtimeError('RT-INVALID-CSV-ERROR',{
detail: err.toString()
}));
});
Expand Down
2 changes: 1 addition & 1 deletion lib/adapters/parsers/json.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ module.exports = base.extend({
resolve();
})
.on('fail', function(err) {
reject(errors.compileError('RT-INVALID-JSON-ERROR',{
reject(errors.runtimeError('RT-INVALID-JSON-ERROR',{
detail: err.toString()
}));
});
Expand Down
2 changes: 1 addition & 1 deletion lib/adapters/parsers/jsonl.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ module.exports = base.extend({
});

parser.on("error", function(err) {
reject(errors.compileError('RT-INVALID-JSONL-ERROR',{
reject(errors.runtimeError('RT-INVALID-JSONL-ERROR',{
detail: err.toString()
}));
});
Expand Down
4 changes: 3 additions & 1 deletion lib/strings/juttle-error-strings-en-US.json
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,8 @@
"RT-MODULE-NOT-FOUND": "Error: could not find module \"{{info.module}}\"",
"RT-FIELD-NOT-STRING": "Error: field {{info.field}} is not a string",
"RT-INVALID-OPTION-VALUE": "Error: Invalid {{info.option}} option value, must be one of the following: {{info.supported}}",
"RT-INVALID-VIEW": "Error: program refers to invalid client view \"{{info.sink}}\""
"RT-INVALID-VIEW": "Error: program refers to invalid client view \"{{info.sink}}\"",
"RT-OPTION-SHOULD-BE-POSITIVE-INTEGER": "Error: option {{info.option}} should be a positive integer",
"RT-OPTION-VALUE-EXCEEDED": "Error: option {{info.option}} exceeded limit of {{info.value}}{{info.extra}}"
}
}
Loading