Skip to content
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

Added sails socket connection mutex #27

Open
wants to merge 38 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
045c940
Fixed multiple quick initial requests causing failed sails connection…
t3rminus Aug 12, 2015
5edf809
- Cleared mutex before completing callbacks
t3rminus Aug 12, 2015
4169ef7
Created bc-ember-data-sails branch, updated name
t3rminus Aug 13, 2015
7df4169
Updated remote to reflect branch
t3rminus Aug 13, 2015
87b5f65
2.0 compatibility
Aug 18, 2015
7f9c0fe
Ember-data 2.0 compatibility
Aug 18, 2015
45b99fa
updated sails-socket to work with the new pushData function
Aug 19, 2015
3612045
Updated pushPayload to use the new ember-data 2.0 method
Aug 19, 2015
da97112
reset packages.json
Aug 19, 2015
d3233f5
Merge commit '87b5f655855a9788bb44f2e95c675d09abd4f0b8' into bc-ember…
Sep 9, 2015
f1108a1
Merge commit 'bc9c9849766b45fcba4c45f93196d61c347bd5b7'
t3rminus Nov 24, 2015
e51db60
Merge branch 'master' into bc-ember-data-sails
t3rminus Nov 24, 2015
5f8360c
updated push function to handle arrays
Nov 24, 2015
977e2d3
[FIX] Ember.String.fmt deprecations
Nov 24, 2015
4dbeec8
Merge commit '977e2d3047840f6366fe460ea776c702161652f5'
t3rminus Nov 24, 2015
ad1b427
Revert package.son
t3rminus Nov 24, 2015
438b943
Allowed listeners to be added even if you don't need a subscribeEndpo…
Nov 25, 2015
ab3ef47
Use the `ember-data` initializer as a target instead of the soon to b…
bmac Dec 12, 2016
f85faa9
Merge pull request #1 from bmac/patch-2
Feb 15, 2017
4717aa8
[FIX] deprecation warnings for ember 2.0
mukk85 Feb 21, 2017
d103bf4
fixed tests
mukk85 Feb 21, 2017
04ec51d
Updated ember
mukk85 Feb 21, 2017
2f0f33a
bumped version
mukk85 Feb 21, 2017
3a93bc8
code format fixes
mukk85 Mar 1, 2017
bf698ce
updated to match new ember-embedded-records mixin syntax
mukk85 Apr 8, 2017
e54cea4
[FIX] reconnect error
mukk85 May 5, 2017
473133f
removed deprecated store.findById
mukk85 Jun 15, 2017
74ecd5c
[FIX] Hanging on re-connect, because events weren't properly being re…
t3rminus Aug 3, 2017
7fa0b00
[FIX] Added link to repo
t3rminus Aug 3, 2017
f29e1ed
[IMP] removed deprecation warnings
mukk85 Apr 5, 2018
63c710e
[FIX] updated warning and debug messages to use new ember style
mukk85 Sep 5, 2018
33decf9
[UPD] Updated to latest ember-cli
mukk85 Sep 5, 2018
5e1d680
version bump
mukk85 Sep 5, 2018
3b42605
[FIX] debug and info messages
mukk85 Sep 5, 2018
7f1fce2
fix code style
mukk85 Oct 3, 2018
a3635d9
updating ember-cli
mukk85 Oct 3, 2018
047dc43
[NEW] renamed package and added to namespace
mukk85 Oct 3, 2018
eb0a14b
[FIX] updated missing namespaces
mukk85 Oct 3, 2018
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
5 changes: 2 additions & 3 deletions addon/adapters/sails-base.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import WithLoggerMixin from '../mixins/with-logger';


var EmberString = Ember.String;
var fmt = EmberString.fmt;
var pluralize = EmberString.pluralize;
var camelize = EmberString.camelize;
var run = Ember.run;
Expand Down Expand Up @@ -103,7 +102,7 @@ export default DS.RESTAdapter.extend(Ember.Evented, WithLoggerMixin, {
processRequest = bind(this, function () {
return this._request(out, url, method, options)
.then(bind(this, function (response) {
this.info(fmt('%@ %@ request on %@: SUCCESS', out.protocol, method, url));
this.info(`${out.protocol} ${method} request on ${url}: SUCCESS`);
this.debug(' → request:', options.data);
this.debug(' ← response:', response);
if (this.isErrorObject(response)) {
Expand All @@ -115,7 +114,7 @@ export default DS.RESTAdapter.extend(Ember.Evented, WithLoggerMixin, {
return response;
}))
.catch(bind(this, function (error) {
this.warn(fmt('%@ %@ request on %@: ERROR', out.protocol, method, url));
this.warn(`${out.protocol} ${method} request on ${url}: ERROR`);
this.info(' → request:', options.data);
this.info(' ← error:', error);
return RSVP.reject(error);
Expand Down
10 changes: 5 additions & 5 deletions addon/adapters/sails-socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import Ember from 'ember';
import SailsBaseAdapter from './sails-base';

var EmberString = Ember.String;
var fmt = EmberString.fmt;
var camelize = EmberString.camelize;
var pluralize = EmberString.pluralize;
var run = Ember.run;
Expand All @@ -18,6 +17,7 @@ var debounce = run.debounce;
* @constructor
*/
export default SailsBaseAdapter.extend({
store: Ember.inject.service(),
/**
* Holds the scheduled subscriptions
* @since 0.0.11
Expand Down Expand Up @@ -124,7 +124,7 @@ export default SailsBaseAdapter.extend({
record.id = message.id;
}
payload[pluralize(camelize(type.modelName))] = [record];
store.pushPayload(type, payload);
store.pushPayload(type.modelName, payload);
},

/**
Expand Down Expand Up @@ -169,8 +169,8 @@ export default SailsBaseAdapter.extend({
var eventName = camelize(model).toLowerCase();
var socket = this.sailsSocket;
if (socket.listenFor(eventName, true)) {
this.notice(fmt('setting up adapter to listen for `%@` messages', model));
store = this.container.lookup('store:main');
this.notice(`setting up adapter to listen for ${model} messages`);
store = this.get('store');
type = store.modelFor(model);
socket.on(eventName + '.created', bind(this, '_handleSocketRecordCreated', store, type));
socket.on(eventName + '.updated', bind(this, '_handleSocketRecordUpdated', store, type));
Expand Down Expand Up @@ -227,7 +227,7 @@ export default SailsBaseAdapter.extend({
payload[k] = Object.keys(data[k]);
this._listenToSocket(k);
}
self.debug(fmt('asking the API to subscribe to some records of type %@', Ember.keys(data).join(', ')));
self.debug(`asking the API to subscribe to some records of type ${Object.keys(data).join(', ')}`);
// ask the API to subscribe to those records
this.fetchCSRFToken().then(function () {
self.checkCSRF(payload);
Expand Down
24 changes: 15 additions & 9 deletions addon/mixins/store.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,16 +28,22 @@ var StoreMixin = Ember.Mixin.create({
* @method push
* @inheritDoc
*/
push: function (typeName/*, data, _partial*/) {
var res = this._super.apply(this, arguments), id, type, adapter;
if (this._pushSubscribes && res && (id = res.get('id'))) {
type = this.modelFor(typeName);
adapter = this.adapterFor(type);
if(adapter instanceof SailsSocketAdapter)
{
adapter._scheduleSubscribe(type, id);
push: function (results/*, data, _partial*/) {
/* jshint unused:false */
var res = this._super.apply(this, arguments), id, type, adapter,
resArray = Array.isArray(res) ? res : [res],
Copy link
Owner

Choose a reason for hiding this comment

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

You're missing the test on _pushSubscribes on the refactored code. I am on my phone and that is a long time I did not work on this addon but I believe it has to be there because depending on settings it should or not subscribe

self = this;

resArray.forEach(function (res) {
if (res && (id = res.get('id'))) {
type = self.modelFor(res.constructor.modelName);
adapter = self.adapterFor(res.constructor.modelName);
if (adapter instanceof SailsSocketAdapter) {
adapter._scheduleSubscribe(type, id);
}
}
}
});

return res;
},

Expand Down
19 changes: 9 additions & 10 deletions addon/serializers/sails.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import SailsSocketAdapter from 'ember-data-sails/adapters/sails-socket';

var $ = Ember.$;
var EmberString = Ember.String;
var fmt = EmberString.fmt;
var pluralize = EmberString.pluralize;
var computed = Ember.computed;

Expand Down Expand Up @@ -44,7 +43,7 @@ var SailsSerializer = DS.RESTSerializer.extend(WithLogger, {
* @method extractArray
* @inheritDoc
*/
extractArray: blueprintsWrapMethod(function (store, primaryType, payload) {
normalizeArrayResponse: blueprintsWrapMethod(function (store, primaryType, payload) {
var newPayload = {};
newPayload[pluralize(primaryType.modelName)] = payload;
return this._super(store, primaryType, newPayload);
Expand All @@ -55,7 +54,7 @@ var SailsSerializer = DS.RESTSerializer.extend(WithLogger, {
* @method extractSingle
* @inheritDoc
*/
extractSingle: blueprintsWrapMethod(function (store, primaryType, payload, recordId) {
normalizeSingleResponse: blueprintsWrapMethod(function (store, primaryType, payload, recordId) {
var newPayload;
if (payload === null) {
return this._super.apply(this, arguments);
Expand All @@ -70,7 +69,7 @@ var SailsSerializer = DS.RESTSerializer.extend(WithLogger, {
* @method extractDeleteRecord
* @inheritDoc
*/
extractDeleteRecord: blueprintsWrapMethod(function (store, type, payload, id, requestType) {
normalizeDeleteRecordResponse: blueprintsWrapMethod(function (store, type, payload, id, requestType) {
return this._super(store, type, null, id, requestType);
}),

Expand All @@ -81,9 +80,9 @@ var SailsSerializer = DS.RESTSerializer.extend(WithLogger, {
*/
serializeIntoHash: blueprintsWrapMethod(function (data, type, record, options) {
var json;
if (Ember.keys(data).length > 0) {
if (Object.keys(data).length > 0) {
this.error(
fmt('trying to serialize multiple records in one hash for type %@', type.modelName),
`trying to serialize multiple records in one hash for type ${type.modelName}`,
data
);
throw new Error('Sails does not accept putting multiple records in one hash');
Expand All @@ -108,7 +107,7 @@ var SailsSerializer = DS.RESTSerializer.extend(WithLogger, {
* @method extract
* @inheritDoc
*/
extract: function (store, type/*, payload, id, requestType*/) {
normalizeResponse: function (store, type/*, payload, id, requestType*/) {
var adapter, modelName, isUsingSocketAdapter;
// this is the only place we have access to the store, so that we can get the adapter and check
// if it is an instance of sails socket adapter, and so register for events if necessary on that
Expand Down Expand Up @@ -146,7 +145,7 @@ var SailsSerializer = DS.RESTSerializer.extend(WithLogger, {
if ((data = hash[key])) {
if (rel.kind === 'belongsTo') {
if (Ember.typeOf(hash[key]) === 'object') {
self.debug(fmt('found 1 embedded %@ record:', modelName), hash[key]);
self.debug(`found 1 embedded ${modelName} record:`, hash[key]);
delete hash[key];
serializer = store.serializerFor(modelName);
self.store.push(rel.type, serializer.normalize(rel.type, data, null));
Expand All @@ -157,15 +156,15 @@ var SailsSerializer = DS.RESTSerializer.extend(WithLogger, {
serializer = store.serializerFor(modelName);
hash[key] = data.map(function (item) {
if (Ember.typeOf(item) === 'object') {
self.debug(fmt('found 1 embedded %@ record:', modelName), item);
self.debug(`found 1 embedded ${modelName} record:`, item);
self.store.push(rel.type, serializer.normalize(rel.type, item, null));
return item.id;
}
return item;
});
}
else {
self.warn(fmt('unknown relationship kind %@:', rel.kind), rel);
self.warn(`unknown relationship kind ${rel.kind}:`, rel);
throw new Error('Unknown relationship kind ' + rel.kind);
}
}
Expand Down
23 changes: 16 additions & 7 deletions addon/services/sails-socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ var run = Ember.run;
var bind = run.bind;
var next = run.next;
var later = run.later;
var EmberString = Ember.String;
var fmt = EmberString.fmt;

/**
* Shortcut to know if an object is alive or not
Expand Down Expand Up @@ -202,7 +200,7 @@ var SailsSocketService = Ember.Object.extend(Ember.Evented, WithLoggerMixin, {
reject(error ? error : new Ember.Error('Sails socket service destroyed'));
}
});
}, fmt('getting the connected Sails socket for `%@` request on %@', method, args[0]));
}, `getting the connected Sails socket for ${method} request on ${args[0]}`);
},

/**
Expand All @@ -211,7 +209,7 @@ var SailsSocketService = Ember.Object.extend(Ember.Evented, WithLoggerMixin, {
* @inheritDoc
*/
trigger: function (event/*, arg*/) {
this.debug(fmt('triggering event `%@`', event));
this.debug(`triggering event ${event}`);
return this._super.apply(this, arguments);
},

Expand All @@ -234,8 +232,19 @@ var SailsSocketService = Ember.Object.extend(Ember.Evented, WithLoggerMixin, {
}
else {
this.info('socket not connected, listening for connect event before giving it');
if(!this._waitingForSockets) {
this._waitingForSockets = [];
}
this._waitingForSockets.push(callback);
if(this._waitingForSockets.length > 1) {
return;
}
this.one('didConnect', bind(this, function () {
callback.call(this, null, this._sailsSocket);
var callbacks = this._waitingForSockets;
delete this._waitingForSockets;
for(var i = 0; i < callbacks.length; i++) {
callbacks[i].call(this, null, this._sailsSocket);
}
}));
if (this.get('isInitialized')) {
this.info('looks like we are initialized but not connected, reconnecting socket');
Expand Down Expand Up @@ -273,7 +282,7 @@ var SailsSocketService = Ember.Object.extend(Ember.Evented, WithLoggerMixin, {
if (!(meta = this._listeners[event]).isListening) {
this._sailsSocket._raw.addEventListener(event, meta.method);
meta.isListening = true;
this.info(fmt('attached event `%@` on socket', event));
this.info(`attached event ${event} on socket`);
}
}
return this;
Expand All @@ -293,7 +302,7 @@ var SailsSocketService = Ember.Object.extend(Ember.Evented, WithLoggerMixin, {
if ((meta = this._listeners[event]).isListening) {
this._sailsSocket._raw.removeEventListener(event, meta.method);
meta.isListening = false;
this.info(fmt('detached event `%@` from socket', event));
this.info(`detached event ${event} from socket`);
}
}
return this;
Expand Down