| OLD | NEW |
| 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file | 1 // Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file |
| 2 // for details. All rights reserved. Use of this source code is governed by a | 2 // for details. All rights reserved. Use of this source code is governed by a |
| 3 // BSD-style license that can be found in the LICENSE file. | 3 // BSD-style license that can be found in the LICENSE file. |
| 4 | 4 |
| 5 library chat_server; | 5 library chat_server; |
| 6 import 'dart:async'; | 6 import 'dart:async'; |
| 7 import 'dart:io'; | 7 import 'dart:io'; |
| 8 import 'dart:isolate'; | 8 import 'dart:isolate'; |
| 9 import 'dart:json' as json; | 9 import 'dart:json' as json; |
| 10 import 'dart:math'; | 10 import 'dart:math'; |
| (...skipping 46 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 57 | 57 |
| 58 | 58 |
| 59 class User { | 59 class User { |
| 60 static int nextSessionId = 0; | 60 static int nextSessionId = 0; |
| 61 | 61 |
| 62 User(this._handle) { | 62 User(this._handle) { |
| 63 _sessionId = "a${nextSessionId++}"; | 63 _sessionId = "a${nextSessionId++}"; |
| 64 markActivity(); | 64 markActivity(); |
| 65 } | 65 } |
| 66 | 66 |
| 67 void markActivity() { _lastActive = new Date.now(); } | 67 void markActivity() { _lastActive = new DateTime.now(); } |
| 68 Duration idleTime(Date now) => now.difference(_lastActive); | 68 Duration idleTime(DateTime now) => now.difference(_lastActive); |
| 69 | 69 |
| 70 String get handle => _handle; | 70 String get handle => _handle; |
| 71 String get sessionId => _sessionId; | 71 String get sessionId => _sessionId; |
| 72 | 72 |
| 73 String _handle; | 73 String _handle; |
| 74 String _sessionId; | 74 String _sessionId; |
| 75 Date _lastActive; | 75 DateTime _lastActive; |
| 76 } | 76 } |
| 77 | 77 |
| 78 | 78 |
| 79 class Message { | 79 class Message { |
| 80 static const int JOIN = 0; | 80 static const int JOIN = 0; |
| 81 static const int MESSAGE = 1; | 81 static const int MESSAGE = 1; |
| 82 static const int LEAVE = 2; | 82 static const int LEAVE = 2; |
| 83 static const int TIMEOUT = 3; | 83 static const int TIMEOUT = 3; |
| 84 static const List<String> _typeName = | 84 static const List<String> _typeName = |
| 85 const [ "join", "message", "leave", "timeout"]; | 85 const [ "join", "message", "leave", "timeout"]; |
| 86 | 86 |
| 87 Message.join(this._from) | 87 Message.join(this._from) |
| 88 : _received = new Date.now(), _type = JOIN; | 88 : _received = new DateTime.now(), _type = JOIN; |
| 89 Message(this._from, this._message) | 89 Message(this._from, this._message) |
| 90 : _received = new Date.now(), _type = MESSAGE; | 90 : _received = new DateTime.now(), _type = MESSAGE; |
| 91 Message.leave(this._from) | 91 Message.leave(this._from) |
| 92 : _received = new Date.now(), _type = LEAVE; | 92 : _received = new DateTime.now(), _type = LEAVE; |
| 93 Message.timeout(this._from) | 93 Message.timeout(this._from) |
| 94 : _received = new Date.now(), _type = TIMEOUT; | 94 : _received = new DateTime.now(), _type = TIMEOUT; |
| 95 | 95 |
| 96 User get from => _from; | 96 User get from => _from; |
| 97 Date get received => _received; | 97 DateTime get received => _received; |
| 98 String get message => _message; | 98 String get message => _message; |
| 99 void set messageNumber(int n) { _messageNumber = n; } | 99 void set messageNumber(int n) { _messageNumber = n; } |
| 100 | 100 |
| 101 Map toMap() { | 101 Map toMap() { |
| 102 Map map = new Map(); | 102 Map map = new Map(); |
| 103 map["from"] = _from.handle; | 103 map["from"] = _from.handle; |
| 104 map["received"] = _received.toString(); | 104 map["received"] = _received.toString(); |
| 105 map["type"] = _typeName[_type]; | 105 map["type"] = _typeName[_type]; |
| 106 if (_type == MESSAGE) map["message"] = _message; | 106 if (_type == MESSAGE) map["message"] = _message; |
| 107 map["number"] = _messageNumber; | 107 map["number"] = _messageNumber; |
| 108 return map; | 108 return map; |
| 109 } | 109 } |
| 110 | 110 |
| 111 User _from; | 111 User _from; |
| 112 Date _received; | 112 DateTime _received; |
| 113 int _type; | 113 int _type; |
| 114 String _message; | 114 String _message; |
| 115 int _messageNumber; | 115 int _messageNumber; |
| 116 } | 116 } |
| 117 | 117 |
| 118 | 118 |
| 119 class Topic { | 119 class Topic { |
| 120 static const int DEFAULT_IDLE_TIMEOUT = 60 * 60 * 1000; // One hour. | 120 static const int DEFAULT_IDLE_TIMEOUT = 60 * 60 * 1000; // One hour. |
| 121 Topic() | 121 Topic() |
| 122 : _activeUsers = new Map(), | 122 : _activeUsers = new Map(), |
| (...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 189 } | 189 } |
| 190 } | 190 } |
| 191 | 191 |
| 192 void registerChangeCallback(String sessionId, var callback) { | 192 void registerChangeCallback(String sessionId, var callback) { |
| 193 _callbacks[sessionId] = callback; | 193 _callbacks[sessionId] = callback; |
| 194 } | 194 } |
| 195 | 195 |
| 196 void _handleTimer(Timer timer) { | 196 void _handleTimer(Timer timer) { |
| 197 Set inactiveSessions = new Set(); | 197 Set inactiveSessions = new Set(); |
| 198 // Collect all sessions which have not been active for some time. | 198 // Collect all sessions which have not been active for some time. |
| 199 Date now = new Date.now(); | 199 DateTime now = new DateTime.now(); |
| 200 _activeUsers.forEach((String sessionId, User user) { | 200 _activeUsers.forEach((String sessionId, User user) { |
| 201 if (user.idleTime(now).inMilliseconds > DEFAULT_IDLE_TIMEOUT) { | 201 if (user.idleTime(now).inMilliseconds > DEFAULT_IDLE_TIMEOUT) { |
| 202 inactiveSessions.add(sessionId); | 202 inactiveSessions.add(sessionId); |
| 203 } | 203 } |
| 204 }); | 204 }); |
| 205 // Terminate the inactive sessions. | 205 // Terminate the inactive sessions. |
| 206 inactiveSessions.forEach((String sessionId) { | 206 inactiveSessions.forEach((String sessionId) { |
| 207 Function callback = _callbacks.remove(sessionId); | 207 Function callback = _callbacks.remove(sessionId); |
| 208 if (callback != null) callback(null); | 208 if (callback != null) callback(null); |
| 209 User user = _activeUsers.remove(sessionId); | 209 User user = _activeUsers.remove(sessionId); |
| (...skipping 285 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 495 if (sessionId != null && nextMessage != null) { | 495 if (sessionId != null && nextMessage != null) { |
| 496 | 496 |
| 497 void sendResponse(messages) { | 497 void sendResponse(messages) { |
| 498 // Send response. | 498 // Send response. |
| 499 Map responseData = new Map(); | 499 Map responseData = new Map(); |
| 500 responseData["response"] = "receive"; | 500 responseData["response"] = "receive"; |
| 501 if (messages != null) { | 501 if (messages != null) { |
| 502 responseData["messages"] = messages; | 502 responseData["messages"] = messages; |
| 503 responseData["activeUsers"] = _topic.activeUsers; | 503 responseData["activeUsers"] = _topic.activeUsers; |
| 504 responseData["upTime"] = | 504 responseData["upTime"] = |
| 505 new Date.now().difference(_serverStart).inMilliseconds; | 505 new DateTime.now().difference(_serverStart).inMilliseconds; |
| 506 } else { | 506 } else { |
| 507 responseData["disconnect"] = true; | 507 responseData["disconnect"] = true; |
| 508 } | 508 } |
| 509 _sendJSONResponse(response, responseData); | 509 _sendJSONResponse(response, responseData); |
| 510 } | 510 } |
| 511 | 511 |
| 512 // Receive request from user. | 512 // Receive request from user. |
| 513 List messages = _topic.messagesFrom(nextMessage, maxMessages); | 513 List messages = _topic.messagesFrom(nextMessage, maxMessages); |
| 514 if (messages == null) { | 514 if (messages == null) { |
| 515 _topic.registerChangeCallback(sessionId, sendResponse); | 515 _topic.registerChangeCallback(sessionId, sendResponse); |
| 516 } else { | 516 } else { |
| 517 sendResponse(messages); | 517 sendResponse(messages); |
| 518 } | 518 } |
| 519 | 519 |
| 520 } else { | 520 } else { |
| 521 _protocolError(request, response); | 521 _protocolError(request, response); |
| 522 } | 522 } |
| 523 } else { | 523 } else { |
| 524 _protocolError(request, response); | 524 _protocolError(request, response); |
| 525 } | 525 } |
| 526 }; | 526 }; |
| 527 } | 527 } |
| 528 | 528 |
| 529 void init() { | 529 void init() { |
| 530 _logRequests = false; | 530 _logRequests = false; |
| 531 _topic = new Topic(); | 531 _topic = new Topic(); |
| 532 _serverStart = new Date.now(); | 532 _serverStart = new DateTime.now(); |
| 533 _messageCount = 0; | 533 _messageCount = 0; |
| 534 _messageRate = new Rate(); | 534 _messageRate = new Rate(); |
| 535 | 535 |
| 536 // Start a timer for cleanup events. | 536 // Start a timer for cleanup events. |
| 537 _cleanupTimer = | 537 _cleanupTimer = |
| 538 new Timer.repeating(10000, (timer) => _topic._handleTimer(timer)); | 538 new Timer.repeating(10000, (timer) => _topic._handleTimer(timer)); |
| 539 } | 539 } |
| 540 | 540 |
| 541 // Start timer for periodic logging. | 541 // Start timer for periodic logging. |
| 542 void _handleLogging(Timer timer) { | 542 void _handleLogging(Timer timer) { |
| (...skipping 66 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... |
| 609 } | 609 } |
| 610 | 610 |
| 611 String _host; | 611 String _host; |
| 612 int _port; | 612 int _port; |
| 613 HttpServer _server; // HTTP server instance. | 613 HttpServer _server; // HTTP server instance. |
| 614 bool _logRequests; | 614 bool _logRequests; |
| 615 | 615 |
| 616 Topic _topic; | 616 Topic _topic; |
| 617 Timer _cleanupTimer; | 617 Timer _cleanupTimer; |
| 618 Timer _loggingTimer; | 618 Timer _loggingTimer; |
| 619 Date _serverStart; | 619 DateTime _serverStart; |
| 620 | 620 |
| 621 bool _logging; | 621 bool _logging; |
| 622 int _messageCount; | 622 int _messageCount; |
| 623 Rate _messageRate; | 623 Rate _messageRate; |
| 624 | 624 |
| 625 // Static HTML. | 625 // Static HTML. |
| 626 List<int> _redirectPage; | 626 List<int> _redirectPage; |
| 627 List<int> _notFoundPage; | 627 List<int> _notFoundPage; |
| 628 } | 628 } |
| 629 | 629 |
| 630 | 630 |
| 631 // Calculate the rate of events over a given time range. The time | 631 // Calculate the rate of events over a given time range. The time |
| 632 // range is split over a number of buckets where each bucket collects | 632 // range is split over a number of buckets where each bucket collects |
| 633 // the number of events happening in that time sub-range. The first | 633 // the number of events happening in that time sub-range. The first |
| 634 // constructor arument specifies the time range in milliseconds. The | 634 // constructor arument specifies the time range in milliseconds. The |
| 635 // buckets are in the list _buckets organized at a circular buffer | 635 // buckets are in the list _buckets organized at a circular buffer |
| 636 // with _currentBucket marking the bucket where an event was last | 636 // with _currentBucket marking the bucket where an event was last |
| 637 // recorded. A current sum of the content of all buckets except the | 637 // recorded. A current sum of the content of all buckets except the |
| 638 // one pointed a by _currentBucket is kept in _sum. | 638 // one pointed a by _currentBucket is kept in _sum. |
| 639 class Rate { | 639 class Rate { |
| 640 Rate([int timeRange = 1000, int buckets = 10]) | 640 Rate([int timeRange = 1000, int buckets = 10]) |
| 641 : _timeRange = timeRange, | 641 : _timeRange = timeRange, |
| 642 _buckets = new List.fixedLength(buckets + 1), // Current bucket is not
in the sum. | 642 _buckets = new List.fixedLength(buckets + 1), // Current bucket is not
in the sum. |
| 643 _currentBucket = 0, | 643 _currentBucket = 0, |
| 644 _currentBucketTime = new Date.now().millisecondsSinceEpoch, | 644 _currentBucketTime = new DateTime.now().millisecondsSinceEpoch, |
| 645 _sum = 0 { | 645 _sum = 0 { |
| 646 _bucketTimeRange = (_timeRange / buckets).toInt(); | 646 _bucketTimeRange = (_timeRange / buckets).toInt(); |
| 647 for (int i = 0; i < _buckets.length; i++) { | 647 for (int i = 0; i < _buckets.length; i++) { |
| 648 _buckets[i] = 0; | 648 _buckets[i] = 0; |
| 649 } | 649 } |
| 650 } | 650 } |
| 651 | 651 |
| 652 // Record the specified number of events. | 652 // Record the specified number of events. |
| 653 void record(int count) { | 653 void record(int count) { |
| 654 _timePassed(); | 654 _timePassed(); |
| 655 _buckets[_currentBucket] = _buckets[_currentBucket] + count; | 655 _buckets[_currentBucket] = _buckets[_currentBucket] + count; |
| 656 } | 656 } |
| 657 | 657 |
| 658 // Returns the current rate of events for the time range. | 658 // Returns the current rate of events for the time range. |
| 659 num get rate { | 659 num get rate { |
| 660 _timePassed(); | 660 _timePassed(); |
| 661 return _sum; | 661 return _sum; |
| 662 } | 662 } |
| 663 | 663 |
| 664 // Update the current sum as time passes. If time has passed by the | 664 // Update the current sum as time passes. If time has passed by the |
| 665 // current bucket add it to the sum and move forward to the bucket | 665 // current bucket add it to the sum and move forward to the bucket |
| 666 // matching the current time. Subtract all buckets vacated from the | 666 // matching the current time. Subtract all buckets vacated from the |
| 667 // sum as bucket for current time is located. | 667 // sum as bucket for current time is located. |
| 668 void _timePassed() { | 668 void _timePassed() { |
| 669 int time = new Date.now().millisecondsSinceEpoch; | 669 int time = new DateTime.now().millisecondsSinceEpoch; |
| 670 if (time < _currentBucketTime + _bucketTimeRange) { | 670 if (time < _currentBucketTime + _bucketTimeRange) { |
| 671 // Still same bucket. | 671 // Still same bucket. |
| 672 return; | 672 return; |
| 673 } | 673 } |
| 674 | 674 |
| 675 // Add collected bucket to the sum. | 675 // Add collected bucket to the sum. |
| 676 _sum += _buckets[_currentBucket]; | 676 _sum += _buckets[_currentBucket]; |
| 677 | 677 |
| 678 // Find the bucket for the current time. Subtract all buckets | 678 // Find the bucket for the current time. Subtract all buckets |
| 679 // reused from the sum. | 679 // reused from the sum. |
| 680 while (time >= _currentBucketTime + _bucketTimeRange) { | 680 while (time >= _currentBucketTime + _bucketTimeRange) { |
| 681 _currentBucket = (_currentBucket + 1) % _buckets.length; | 681 _currentBucket = (_currentBucket + 1) % _buckets.length; |
| 682 _sum -= _buckets[_currentBucket]; | 682 _sum -= _buckets[_currentBucket]; |
| 683 _buckets[_currentBucket] = 0; | 683 _buckets[_currentBucket] = 0; |
| 684 _currentBucketTime += _bucketTimeRange; | 684 _currentBucketTime += _bucketTimeRange; |
| 685 } | 685 } |
| 686 } | 686 } |
| 687 | 687 |
| 688 int _timeRange; | 688 int _timeRange; |
| 689 List<int> _buckets; | 689 List<int> _buckets; |
| 690 int _currentBucket; | 690 int _currentBucket; |
| 691 int _currentBucketTime; | 691 int _currentBucketTime; |
| 692 num _bucketTimeRange; | 692 num _bucketTimeRange; |
| 693 int _sum; | 693 int _sum; |
| 694 } | 694 } |
| OLD | NEW |