-
Notifications
You must be signed in to change notification settings - Fork 7
/
qlobber-fsq.js
1472 lines (1173 loc) · 51.9 KB
/
qlobber-fsq.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
# qlobber-fsq [![Build Status](https://travis-ci.org/davedoesdev/qlobber-fsq.png)](https://travis-ci.org/davedoesdev/qlobber-fsq) [![Coverage Status](https://coveralls.io/repos/davedoesdev/qlobber-fsq/badge.png?branch=master)](https://coveralls.io/r/davedoesdev/qlobber-fsq?branch=master) [![NPM version](https://badge.fury.io/js/qlobber-fsq.png)](http://badge.fury.io/js/qlobber-fsq)
Shared file system queue for Node.js.
- Supports pub-sub and work queues.
- Supports local file system for multi-core use.
- Tested with [FraunhoferFS (BeeGFS)](http://www.fhgfs.com/) and [CephFS](http://ceph.com/ceph-storage/file-system/) for distributed use.
- Highly configurable.
- Full set of unit tests, including stress tests.
- Use as a backend-less alternative to [RabbitMQ](http://www.rabbitmq.com/), [Redis pub-sub](http://redis.io/topics/pubsub) etc.
- Supports AMQP-like topics with single- and multi-level wildcards.
- Tested on Linux and Windows.
Example:
```javascript
var QlobberFSQ = require('qlobber-fsq').QlobberFSQ;
var fsq = new QlobberFSQ({ fsq_dir: '/shared/fsq' });
fsq.subscribe('foo.*', function (data, info)
{
console.log(info.topic, data.toString('utf8'));
var assert = require('assert');
assert.equal(info.topic, 'foo.bar');
assert.equal(data, 'hello');
});
fsq.on('start', function ()
{
this.publish('foo.bar', 'hello');
});
```
You can publish messages using a separate process if you like:
```javascript
var QlobberFSQ = require('qlobber-fsq').QlobberFSQ;
var fsq = new QlobberFSQ({ fsq_dir: '/shared/fsq' });
fsq.stop_watching();
fsq.on('stop', function ()
{
this.publish('foo.bar', 'hello');
});
```
Or use the streaming interface to read and write messages:
```javascript
var QlobberFSQ = require('qlobber-fsq').QlobberFSQ;
var fsq = new QlobberFSQ({ fsq_dir: '/shared/fsq' });
function handler(stream, info)
{
var data = [];
stream.on('readable', function ()
{
var chunk = stream.read();
if (chunk)
{
data.push(chunk);
}
});
stream.on('end', function ()
{
var str = Buffer.concat(data).toString('utf8');
console.log(info.topic, str);
var assert = require('assert');
assert.equal(info.topic, 'foo.bar');
assert.equal(str, 'hello');
});
}
handler.accept_stream = true;
fsq.subscribe('foo.*', handler);
fsq.on('start', function ()
{
fsq.publish('foo.bar').end('hello');
});
```
The API is described [here](#tableofcontents).
## Installation
```shell
npm install qlobber-fsq
```
## Limitations
- `qlobber-fsq` provides no guarantee that the order messages are given to subscribers is the same as the order in which the messages were written. If you want to maintain message order between readers and writers then you'll need to do it in your application (using ACKs, sliding windows etc).
- `qlobber-fsq` does its best not to lose messages but in exceptional circumstances (e.g. process crash, file system corruption) messages may get dropped. You should design your application to be resilient against dropped messages.
- `qlobber-fsq` makes no assurances about the security or privacy of messages in transit or at rest. It's up to your application to encrypt messages if required.
- `qlobber-fsq` supports Node 0.10 onwards.
## Distributed filesystems
Note: When using a distributed file system with `qlobber-fsq`, ensure that you synchronize the time and date on all the computers you're using.
### FraunhoferFS (BeeGFS)
When using the FraunhoferFS distributed file system, set the following options in `fhgfs-client.conf`:
```
tuneFileCacheType = none
tuneUseGlobalFileLocks = true
```
`qlobber-fsq` has been tested with FraunhoferFS 2014.01 on Ubuntu 14.04 and FraunhoferFS 2012.10 on Ubuntu 13.10.
### CephFS
`qlobber-fsq` has been tested with CephFS 0.80 on Ubuntu 14.04. Note that you'll need to [upgrade your kernel](http://www.yourownlinux.com/2014/04/install-upgrade-to-linux-kernel-3-14-1-in-linux.html) to at least 3.14.1 in order to get the fix for [a bug](http://tracker.ceph.com/issues/7371) in CephFS.
## How it works
![How it works](http://rawgit.davedoesdev.com/davedoesdev/qlobber-fsq/master/diagrams/how_it_works.svg)
Under the directory you specify for `fsq_dir`, `qlobber-fsq` creates the following sub-directories:
- `staging` Whilst it's being published, each message is written to a file in the staging area. The filename itself contains the message's topic, when it expires, whether it should be read by one subscriber or many and a random sequence of characters to make it unique.
- `messages` Once published to the staging area, each message is moved into this directory. `qlobber-fsq` actually creates a number of sub-directories (called buckets) under `messages` and distributes message between buckets according to the hash of their filenames. This helps to reduce the number of directory entries that have to be read when a single message is written.
- `topics` If a message's topic is long, a separate topic file is created for it in this directory.
- `update` This contains one file, `UPDATE`, which is updated with a random sequence of bytes (called a stamp) every time a message is moved into the `messages` directory. `UPDATE` contains a separate stamp for each bucket.
`qlobber-fsq` reads `UPDATE` at regular intervals to determine whether a new message has been written to a bucket. If it has then it processes each filename in the bucket's directory listing.
If the expiry time in the filename has passed then it deletes the message.
If the filename indicates the message can be read by many subscribers:
- If it's processed this filename before then stop processing this filename.
- If the topic in the filename matches any subscribers then call each subscriber with the file's content. It uses [`qlobber`](https://github.com/davedoesdev/qlobber) to pattern match topics to subscribers.
- Remember that we've processed the filename.
If the filename indicates the message can be read by only one subscriber (i.e. work queue semantics):
- Try to lock the file using `flock`. If it fails to lock the file then stop processing this filename.
- If the topic in the filename matches any subscribers then call one subscriber with the file's content.
- Truncate and delete the file before unlocking it. We truncate the file in case of directory caching.
## Licence
[MIT](LICENCE)
## Test
To run the default tests:
```shell
grunt test [--fsq-dir=<path>]
```
If you don't specify `--fsq-dir` then the default will be used (a directory named `fsq` in the `qlobber-fsq` module directory).
To run the stress tests (multiple queues in a single Node process):
```shell
grunt test-stress [--fsq-dir=<path>]
```
To run the multi-process tests (each process publishing and subscribing to different messages):
```shell
grunt test-multi [--fsq-dir=<path>] [--queues=<number of queues>]
```
If you omit `--queues` then one process will be created per core (detected with [`os.cpus()`](http://nodejs.org/api/os.html#os_os_cpus)).
To run the distributed tests (one Node process per remote host, each one publishing and subscribing to different messages);
```shell
grunt test-multi --fsq-dir=<path> --remote=<host1> --remote=<host2>
```
You can specify as many remote hosts as you like. The test uses [`cp-remote`](https://github.com/davedoesdev/cp-remote) to run a module on each remote host. Make sure on each host:
- The `qlobber-fsq` module is installed at the same location.
- Mount the same distributed file system on the directory you specify for `--fsq-dir`. FraunhoferFS and CephFS are the only distributed file systems currently supported.
Please note the multi-process and distributed tests don't run on Windows.
## Lint
```shell
grunt lint
```
## Code Coverage
```shell
grunt coverage [--fsq-dir=<path>]
```
[Instanbul](http://gotwarlost.github.io/istanbul/) results are available [here](http://rawgit.davedoes.com/davedoesdev/qlobber-fsq/master/coverage/lcov-report/index.html).
Coveralls page is [here](https://coveralls.io/r/davedoesdev/qlobber-fsq).
## Benchmarks
To run the benchmark:
```shell
grunt bench [--fsq-dir=<path>] \
--rounds=<number of rounds> \
--size=<message size> \
--ttl=<message time-to-live in seconds> \
(--queues=<number of queues> | \
--remote=<host1> --remote=<host2> ...)
```
If you don't specify `--fsq-dir` then the default will be used (a directory named `fsq` in the `qlobber-fsq` module directory).
If you provide at least one `--remote <host>` argument then the benchmark will be distributed across multiple hosts using [`cp-remote`](https://github.com/davedoesdev/cp-remote). Make sure on each host:
- The `qlobber-fsq` module is installed at the same location.
- Mount the same distributed file system on the directory you specify for `--fsq-dir`. FraunhoferFS is the only distributed file system currently supported.
# API
*/
/*jslint node: true, nomen: true, bitwise: true, unparam: true */
"use strict";
require('graceful-fs');
var stream = require('stream'),
path = require('path'),
crypto = require('crypto'),
util = require('util'),
events = require('events'),
constants = require('constants'),
async = require('async'),
qlobber = require('qlobber'),
Qlobber = qlobber.Qlobber,
QlobberDedup = qlobber.QlobberDedup;
function CollectStream()
{
stream.Writable.call(this);
this.setMaxListeners(0);
this._chunks = [];
this._len = 0;
var ths = this;
this.on('finish', function ()
{
ths.emit('buffer', Buffer.concat(ths._chunks, ths._len));
});
}
util.inherits(CollectStream, stream.Writable);
CollectStream.prototype._write = function (chunk, encoding, callback)
{
this._chunks.push(chunk);
this._len += chunk.length;
callback();
};
/*function sum(buf, start, end)
{
var i, r = 0;
for (i = start; i < end; i += 1)
{
r += buf[i];
}
return r;
}*/
/**
Creates a new `QlobberFSQ` object for publishing and subscribing to a file system queue.
@constructor
@param {Object} [options] Configures the file system queue. Valid properties are listed below:
- `{String} fsq_dir` The path to the file system queue directory. Note that the following sub-directories will be created under this directory if they don't exist: `messages`, `staging`, `topics` and `update`. Defaults to a directory named `fsq` in the `qlobber-fsq` module directory.
- `{Boolean} encode_topics` Whether to hex-encode message topics. Because topic strings form part of message filenames, they're first hex-encoded. If you can ensure that your message topics contain only valid filename characters, set this to `false` to skip encoding.
- `{Integer} split_topic_at` Maximum number of characters in a short topic. Short topics are contained entirely in a message's filename. Long topics are split so the first `split_topic_at` characters go in the filename and the rest are written to a separate file in the `topics` sub-directory. Obviously long topics are less efficient. Defaults to 200, which is the maximum for most common file systems. Note: if your `fsq_dir` is on an [`ecryptfs`](http://ecryptfs.org/) file system then you should set `split_topic_at` to 100.
- `{Integer} bucket_base`, `{Integer} bucket_num_chars` Messages are distributed across different _buckets_ for efficiency. Each bucket is a sub-directory of the `messages` directory. The number of buckets is determined by the `bucket_base` and `bucket_num_chars` options. `bucket_base` is the radix to use for bucket names and `bucket_num_chars` is the number of digits in each name. For example, `bucket_base: 26` and `bucket_num_chars: 4` results in buckets `0000` through `pppp`. Defaults to `base_base: 16` and `bucket_num_chars: 2` (i.e. buckets `00` through `ff`).
- `{Integer} bucket_stamp_size` The number of bytes to write to the `UPDATE` file when a message is published. The `UPDATE` file (in the `update` directory) is used to determine whether any messages have been published without having to scan all the bucket directories. Each bucket has a section in the `UPDATE` file, `bucket_stamp_size` bytes long. When a message is written to a bucket, its section is filled with random bytes. Defaults to 32.
- `{Integer} flags` Extra flags to use when reading and writing files. You shouldn't need to use this option but if you do then it should be a bitwise-or of values in the (undocumented) Node `constants` module (e.g. `constants.O_DIRECT | constants.O_SYNC`). Defaults to 0.
- `{Integer} unique_bytes` Number of random bytes to append to each message's filename (encoded in hex), in order to avoid name clashes. Defaults to 16. If you increase it (or change the algorithm to add some extra information like the hostname), be sure to reduce `split_topic_at` accordingly.
- `{Integer} single_ttl` Default time-to-live (in milliseconds) for messages which should be read by at most one subscriber. This value is added to the current time and the resulting expiry time is put into the message's filename. After the expiry time, the message is ignored and deleted when convenient. Defaults to 1 hour.
- `{Integer} multi_ttl` Default time-to-live (in milliseconds) for messages which can be read by many subscribers. This value is added to the current time and the resulting expiry time is put into the message's filename. After the expiry time, the message is ignored and deleted when convenient. Defaults to 5 seconds.
- `{Integer} poll_interval` `qlobber-fsq` reads the `UPDATE` file at regular intervals to check whether any messages have been written. `poll_interval` is the time (in milliseconds) between each check. Defaults to 1 second.
- `{Boolean} notify` Whether to use [`fs.watch`](http://nodejs.org/api/fs.html#fs_fs_watch_filename_options_listener) to watch for changes to the `UPDATE` file. Note that this will be done in addition to reading it every `poll_interval` milliseconds because `fs.watch` (`inotify` underneath) can be unreliable, especially under high load. Defaults to `true`.
- `{Integer} retry_interval` Some I/O operations can fail with an error indicating they should be retried. `retry_interval` is the time (in milliseconds) to wait before retrying. Dfaults to 1 second.
- `{Integer} message_concurrency` The number of messages in each bucket to process at once. Defaults to 1.
- `{Integer} bucket_concurrency` The number of buckets to process at once. Defaults to 1.
- `{Boolean} dedup` Whether to ensure each handler function is called at most once when a message is received. Defaults to `true`.
- `{Boolean} single` Whether to process messages meant for _at most_ one subscriber (across all `QlobberFSQ` objects), i.e. work queues. This relies on the optional dependency [`fs-ext`](https://github.com/baudehlo/node-fs-ext). Defaults to `true` if `fs-ext` is installed, otherwise `false` (in which case a [`single_disabled`](#qlobberfsqeventssingle_disablederr) event will be emitted).
- `{String} separator` The character to use for separating words in message topics. Defaults to `.`.
- `{String} wildcard_one` The character to use for matching exactly one word in a message topic to a subscriber. Defaults to `*`.
- `{String} wildcard_some` The character to use for matching zero or more words in a message topic to a subscriber. Defaults to `#`.
- `{Function (info, handlers, cb(err, ready, filtered_handlers))} filter` Function called before each message is processed. You can use this to filter the subscribed handler functions to be called for the message (by passing the filtered list as the third argument to `cb`). If you want to ignore the message _at this time_ then pass `false` as the second argument to `cb`. `filter` will be called again later with the same message. Defaults to a function which calls `cb(null, true, handlers)`. `handlers` and `filtered_handlers` are ES6 Sets, or arrays if `options.dedup` is falsey.
*/
function QlobberFSQ(options)
{
events.EventEmitter.call(this);
options = options || {};
this._fsq_dir = options.fsq_dir || path.join(__dirname, '..', 'fsq');
this._msg_dir = this._fsq_dir + path.sep + 'messages';
this._topic_dir = this._fsq_dir + path.sep + 'topics';
this._staging_dir = this._fsq_dir + path.sep + 'staging';
this._update_dir = this._fsq_dir + path.sep + 'update';
this._update_fname = this._update_dir + path.sep + 'UPDATE';
this._encode_topics = options.encode_topics === undefined ? true : options.encode_topics;
this._split_topic_at = options.split_topic_at || 200;
this._bucket_base = options.bucket_base || 16;
this._bucket_num_chars = options.bucket_num_chars || 2;
this._bucket_stamp_size = options.bucket_stamp_size || 32;
this._flags = options.flags || 0;
this._unique_bytes = options.unique_bytes || 16;
this._single_ttl = options.single_ttl || (60 * 60 * 1000); // 1 hour
this._multi_ttl = options.multi_ttl || (5 * 1000); // 5 seconds
this._poll_interval = options.poll_interval || 1000; // 1 second
this._retry_interval = options.retry_interval || 1000; // 1 second
this._message_concurrency = options.message_concurrency || 1;
this._bucket_concurrency = options.bucket_concurrency || 1;
this._do_dedup = options.dedup === undefined ? true : options.dedup;
this._do_single = options.single === undefined ? true : options.single;
if (this._do_dedup)
{
this._matcher = new QlobberDedup(options);
}
else
{
this._matcher = new Qlobber(options);
}
this._leading_byte = new Buffer(1);
var ths = this,
caches = new Map(),
pending = new Map(),
initialized = false,
count,
num_buckets,
buckets = [],
dirs = [this._fsq_dir,
this._staging_dir,
this._update_dir,
this._msg_dir,
this._topic_dir];
this._filter = options.filter || function (info, handlers, cb)
{
cb.call(ths, null, true, handlers);
};
this._error = function (err)
{
if (err)
{
var i, silent = false;
for (i = 1; i < arguments.length; i += 1)
{
if (err.code === arguments[i])
{
silent = true;
break;
}
}
if ((!silent) && !ths.emit('warning', err))
{
console.error(err);
}
}
return err;
};
this._stopped = false;
this._active = true;
this._chkstop = function ()
{
if (this._stopped && this._active)
{
this._active = false;
this.emit('stop');
}
return this._stopped;
};
this._try_again = function (err)
{
// graceful-fs takes care of EAGAIN
return err && (err.code === 'EBUSY');
};
function emit_error(err)
{
ths._active = false;
ths.emit('error', err);
}
function decode_topic(info)
{
if (ths._encode_topics)
{
info.topic = new Buffer(info.topic, 'hex').toString();
}
}
function parse_fname(bucket, fname, cb)
{
var at_pos = fname.lastIndexOf('@'), metadata, info;
if (at_pos < 0) { return cb(); }
metadata = fname.substr(at_pos + 1).split('+');
if (metadata.length !== 4) { return cb(); }
info = {
fname: fname,
path: ths._msg_dir + path.sep + bucket + path.sep + fname,
topic: fname.substr(0, at_pos),
expires: parseInt(metadata[1], 16),
single: metadata[2] === 's'
};
if (metadata[0] === 's')
{
decode_topic(info);
return cb(info);
}
info.topic_path = ths._topic_dir + path.sep + bucket + path.sep + fname;
ths._fs.readFile(info.topic_path,
{ flag: constants.O_RDONLY | ths._flags },
function (err, split)
{
if (ths._error(err)) { return cb(); }
info.topic += split.toString('utf8');
decode_topic(info);
cb(info);
});
}
function close(fd, err, cb)
{
ths._fs.close(fd, function (err2)
{
ths._error(err2);
if (ths._try_again(err2))
{
return setTimeout(function ()
{
close(fd, err, cb);
}, ths._retry_interval);
}
if (cb) { cb(err || err2); }
});
}
function unlock_and_close(fd, err, cb)
{
// close should be enough but just in case
ths._fs.flock(fd, 'un', function (err2)
{
ths._error(err2);
if (ths._try_again(err2))
{
return setTimeout(function ()
{
unlock_and_close(fd, err, cb);
}, ths._retry_interval);
}
close(fd, err || err2, cb);
});
}
function unlink_unlock_and_close(info, fd, err, cb)
{
ths._fs.unlink(info.path, function (err2)
{
// Ignore EBUSY, rely on truncate having happened.
// When we see it again and can't read a byte, we'll unlink again.
ths._error(err2, 'ENOENT');
if (err2 && (err2.code === 'ENOENT'))
{
err2 = null;
}
if (!info.topic_path)
{
return unlock_and_close(fd, err || err2, cb);
}
ths._fs.unlink(info.topic_path, function (err3)
{
ths._error(err3, 'ENOENT');
if (err3 && (err3.code === 'ENOENT'))
{
err3 = null;
}
unlock_and_close(fd, err || err2 || err3, cb);
});
});
}
function collected(handler, info, cb)
{
return function (buf)
{
if (ths._chkstop()) { return; }
handler.call(ths, buf, info, cb);
};
}
function call_handlers(handlers, info, cb)
{
//console.log('call_handlers', require('os').hostname(), info.topic, handlers.length);
var len = ths._do_dedup ? handlers.size : handlers.length;
if ((len === 0) || ths._chkstop()) { return cb(); }
ths._fs.open(info.path,
(info.single ? constants.O_RDWR : constants.O_RDONLY) | ths._flags,
function (err, fd)
{
function multi_callback(err, cb)
{
ths._error(err);
if (cb) { cb(); }
ths._chkstop();
}
var called = false;
function single_callback(err, cb)
{
if (called) { return multi_callback(err, cb); }
called = true;
function cb2(err)
{
if (cb) { cb(err); }
ths._chkstop();
}
function truncate()
{
ths._fs.ftruncate(fd, 0, function (err)
{
ths._error(err);
if (ths._try_again(err))
{
return setTimeout(truncate, ths._retry_interval);
}
//console.log('truncated', info.fname);
unlink_unlock_and_close(info, fd, err, cb2);
});
}
if (ths._error(err))
{
unlock_and_close(fd, null, cb2);
}
else
{
truncate();
}
}
function read()
{
var stream = ths._fs.createReadStream(null,
{
fd: fd,
autoClose: false,
start: 1
}),
hcb = info.single ? single_callback : multi_callback,
handler,
cstream;
stream.setMaxListeners(0);
for (handler of handlers)
{
if (handler.accept_stream)
{
handler.call(ths, stream, info, hcb);
}
else
{
if (!cstream)
{
cstream = new CollectStream();
stream.pipe(cstream);
}
cstream.on('buffer', collected(handler, info, hcb));
}
}
stream.once('end', function ()
{
if (info.single)
{
cb();
}
else
{
close(fd, null, cb);
}
});
stream.once('error', function (err)
{
ths._error(err);
if (info.single)
{
unlock_and_close(fd, null, cb);
}
else
{
close(fd, null, cb);
}
});
}
if (ths._error(err, 'ENOENT'))
{
if (ths._chkstop()) { return cb(); }
return cb(null, err.code === 'ENOENT');
}
if (ths._chkstop()) { return close(fd, null, cb); }
if (info.single)
{
ths._fs.flock(fd, 'exnb', function (err)
{
if (ths._error(err, 'EAGAIN') || ths._chkstop())
{
return close(fd, null, cb);
}
//console.log('locked', info.fname);
var stream = ths._fs.createReadStream(null,
{
fd: fd,
autoClose: false,
start: 0,
end: 1
}),
got_data = false;
stream.on('readable', function ()
{
var data = stream.read();
if (data)
{
got_data = data.length > 0;
}
});
stream.once('end', function ()
{
if (got_data)
{
read();
}
else
{
unlink_unlock_and_close(info, fd, null, cb);
}
});
stream.once('error', function (err)
{
ths._error(err);
unlock_and_close(fd, null, cb);
});
});
}
else
{
read();
}
});
}
function make_info_handler(cache, cache2, pending2)
{
return function (info, next)
{
if (ths._chkstop()) { return next('stopped'); }
var now = Date.now(),
prev_delay = ths._delay,
handlers,
not_seen;
function cb(err, not_found, is_pending)
{
ths._error(err);
if (not_found || is_pending)
{
cache2.delete(info.fname);
}
else
{
cache2.set(info.fname, info);
}
if ((info.single || is_pending) && !not_found)
{
pending2.push(info);
}
setImmediate(next);
}
if (info.expires <= now)
{
return ths._fs.unlink(info.path, function (err)
{
ths._error(err, 'ENOENT');
// Assume file has been removed. If it hasn't and we see it
// again then it will be expired and we'll unlink again.
if (!info.topic_path)
{
return cb(null, true);
}
ths._fs.unlink(info.topic_path, function (err)
{
ths._error(err, 'ENOENT');
cb(null, true);
});
});
}
handlers = ths._matcher.match(info.topic);
not_seen = initialized && !cache.has(info.fname);
if (not_seen)
{
//console.log('not_seen', require('os').hostname(), info.fname, handlers.length);
ths._delay = 0;
}
/*else
{
console.log('seen', require('os').hostname(), info.fname, handlers.length);
}*/
if (info.single)
{
if (!ths._do_single)
{
return cb();
}
ths._filter(info, handlers, function (err, ready, handlers)
{
ths._error(err);
if (!ready)
{
ths._delay = prev_delay;
}
else if (!ths._do_dedup)
{
if (handlers.length > 0)
{
return call_handlers([handlers[0]], info, cb);
}
}
else if (handlers.size > 0)
{
return call_handlers(new Set([handlers.values().next().value]),
info,
cb);
}
cb();
});
}
else if (not_seen)
{
ths._filter(info, handlers, function (err, ready, handlers)
{
ths._error(err);
if (!ready)
{
ths._delay = prev_delay;
cb(null, false, true);
}
else
{
call_handlers(handlers, info, cb);
}
});
}
else
{
cb();
}
};
}
function make_fname_handler(cache, cache2, pending2)
{
var info_handler = make_info_handler(cache, cache2, pending2);
return function (fname, next)
{
if (ths._chkstop()) { return next('stopped'); }
function cb(info)
{
if (ths._chkstop()) { return next('stopped'); }
if (!info) { return setImmediate(next); }
info_handler(info, next);
}
var info = cache && cache.get(fname);
if (info)
{
return cb(info);
}
parse_fname(cache2.bucket, fname, cb);
};
}
function handle(files, cache, cache2, make_handler, cb)
{
var pending2 = [];
function cb2()
{
if (ths._chkstop()) { return; }
cb(cache2, pending2);
}
if (files.length === 0)
{
return setImmediate(cb2);
}
async.eachLimit(files,
ths._message_concurrency,
make_handler(cache, cache2, pending2),
cb2);
}
this._poll = function ()
{
ths._timeout = null;
if (ths._chkstop()) { return; }
ths._delay = ths._poll_interval;
ths._fs.readFile(ths._update_fname,
{ flag: constants.O_RDONLY | ths._flags },
function (err, update)
{
ths._error(err);
if (ths._chkstop()) { return; }
if (err || (update.length < ths._update_size))
{
ths._timeout = setTimeout(ths._poll, ths._poll_interval);
return;
}
async.eachLimit(buckets, ths._bucket_concurrency,
function (bucket, next)
{
var start = bucket * ths._bucket_stamp_size,
end = (bucket + 1) * ths._bucket_stamp_size,
cache,
bucket_fmt;
//console.log('upsum', require('os').hostname(), sum(update, start, end), bucket);
if (update.slice(start, end).equals(
ths._last_update.slice(start, end)))
{
//console.log('no update', require('os').hostname(), bucket);
cache = caches.get(bucket);
handle(pending.get(bucket), cache, cache, make_info_handler,
function (cache2, pending2)
{
pending.set(bucket, pending2);
next();
});
}
else
{
//console.log('update', require('os').hostname(), bucket);
bucket_fmt = ths._format_bucket(bucket);
ths._fs.readdir(ths._msg_dir + path.sep + bucket_fmt,
function (err, files)
{
ths._error(err);
if (ths._chkstop()) { return; }
if (err) { return next(); }
var empty = new Map();
empty.bucket = bucket_fmt;
handle(files, caches.get(bucket), empty, make_fname_handler,
function (cache2, pending2)
{
update.copy(ths._last_update, start, start, end);
caches.set(bucket, cache2);
pending.set(bucket, pending2);
next();
});
});
}
}, function ()
{
if (ths._chkstop()) { return; }
if (!initialized)
{
initialized = true;
ths.emit('start');
}
if (!ths._chkstop())
{
ths._timeout = setTimeout(ths._poll, ths._delay);
}
});
});
};
this._format_bucket = function (b)