Parse.query on local datastore objects returns other local object attributes or null
Issue Description
Performing a query for objects located in the local datastore sometimes returns other local object attributes or no attributes when there should be attributes for the local object.
Steps to reproduce
Add multiple items with attributes of the same class to the local datastore. Quit and restart the RN app and perform a query for a subset of objects.
Expected Results
The expectation is that the query results contain the matching objects for the query parameters and each object contains the attributes for the object when it was pinned to the local datastore.
Actual Outcome
The query will return fewer objects than it should due to ParseQuery._handleOfflineQuery setting the object._localId after ParseObject.fromJSON. This causes the static cache reference for the object to now point to null or the attributes of another object.
Environment Setup
- JS SDK
- JS SDK version: 2.6.0
- Application? (Browser, Node, React-Native, etc): React-Native
More Info on Solution
I was able to fix this with two changes and I'm asking for feedback or commentary on what other side-effects this may introduce:
Change 1:
In ParseObject._finishFetch the first thing this function does is to set the id of the object if it isn't set already. There's already a check here for the serverData.objectId. I added an additional check for the _localId and set the object's id to the localId of the object if it doesn't have an objectId in the case of locally stored objects only.
if (!this.id && serverData.objectId) {
this.id = serverData.objectId;
} else if (!this.id && serverData._localId) {
this.id = serverData._localId;
}
This seems to be the right place to do this. Without this set here, AFTER the parse object is created using ParseObject.fromJSON during the _handleOfflineQuery operation the next step will then check the object's localId and objectId and reset the _localId to match the attribute of _localId. However, by doing this outside of the .fromJSON call, this has a side effect of changing the reference to the cache attributes and thus returns another object's attributes or empty object for attributes.
Change 2:
The second issue is how attribute values are getting encoded into the cache.
In ObjectStateMutations.js the commitServerChanges function was limiting the attributes to only objects. Thus, if an attribute was a string, it wouldn't be saved to the cache. I changed the check on the val to encode objects and just store the rest as-is. This I'm not clear on what other side-effects this may introduce, but it is now working in my app for strings and bools for attributes.
export function commitServerChanges(serverData
/*: AttributeMap*/
, objectCache
/*: ObjectCache*/
, changes
/*: AttributeMap*/
) {
for (const attr in changes) {
const val = changes[attr];
serverData[attr] = val;
if (val && !(val instanceof ParseObject) && !(val instanceof ParseFile) && !(val instanceof ParseRelation)) {
if (typeof val === 'object') {
const json = encode(val, false, true);
objectCache[attr] = JSON.stringify(json);
} else {
objectCache[attr] = val;
}
}
}
}
Thank you for the detailed post! When developing this we tried to not introduce any breaking changes to the code by changing functions such as fromJSON.
If you are willing to open a PR with failing tests, we will gladly review it.
I'll try to see if I can replicate your issue. If you can create a simple sample repo that would be great.
Hi @dplewis
I'm putting together a demo of the problem, but I'm running into another issue with local storage.
Parse.Object.unPinAllObjects();
Doesn't seems like this is clearing out the local database.
If I do:
await Parse.Object.unPinAllObjects();
const local = await Parse.dumpLocalDatastore();
local always has the local database objects. I can't seem to find a way to actually clear out the local database to finish this demo and get over to you.
Wes
This problem may be related to the issue I'm reporting.
When you Parse.Object.unPinAllObjects(); this will clear the references under _default but it doesn't remove the objects from the top flat list.
Next, when you perform a query, the query will return any object that meets the query params including any object that was created under the _default key but was removed later since it still exists at the top level.
I think this may be the root of the issue. Here's what I think is happening in my case. My app does queries and updates to the local datastore. In this process, objects are pinned and unpinned and updated. Older objects may have attributes that no longer exist as time moves forward, however, there's a series of orphaned objects at the top level of the localDatastore. Then, when performing a query on the localdatastore, the query INCLUDES these orphaned objects as part of the query response. Then, during fromJSON the localIDs are swapped which causes the local object to point to an older (possibly missing) attribute cache that was removed in the past.
I suspect that if the object at the top-level local database store is actually removed when unpinning an object so that _default tracks with the stored objects then this issue might be solved.
Doesn't seems like this is clearing out the local database.
You should be able to use Parse.LocalDatastore._clear()
You can look at the tests here. You can write one to show what you expect the LDS to look like after each operation and see if it passes.
If you have a demo, I'd gladly look at it.
@wfilleman I think I figured out what this issue is. I'll try to submit a PR soon.
Awesome, @dplewis! I've been side-tracked with my project and haven't been able to revisit this. Looking forward to what you found/fixed.
@wfilleman The JSK has a SingleInstanceState for web clients, this mean any objects with the same ObjectId / localId will be synchronized and have the same data.
You can read more about it here
Workaround:
- Save objects before pinning
- Parse.Object.disableSingleInstance();
Possible Solutions:
- _localId to be randomly generated instead of incremented
- cache _localId counter
When you restart your app the localId count resets. This is where your problem arises.
// integration/test/ParseLocalDatastoreTest.js
fit(`${controller.name} can query from pin (unsaved)`, async () => {
Parse.Object.enableSingleInstance(); // emulate web client
const pinned = new TestObject({ foo: 'bar' });
await pinned.pin();
Parse.Object._setLocalCount(10); // emulate reset localcount
const unpinned = new TestObject({ foo: 'baz' });
const query = new Parse.Query(TestObject);
query.fromPin();
const results = await query.find();
console.log(results[0].get('foo')); // baz
assert.equal(results.length, 1);
});
What do you think? @acinader @davimacedo
Thanks @dplewis,
I can't save objects before pinning. I'm using this particular feature of Parse in a local environment scenario where the user doesn't have access to the internet and thus my Parse server. For these clients, the locally pinned objects I specifically do not want to be synced back to my server even when their network allows for an internet connection.
I can try to disableSingleInstance and see if that works for a workaround in my case and report back.
Wes
Hi @dplewis
I attempted to use the Parse.Object.disableSingleInstance(); option, but this didn't help the issues I'm seeing. Which, makes sense according to your root cause analysis where the localID counter is reset back to 0 on app restart. As an experiment, I changed ParseObject.js from:
_getId()
/*: string*/
{
if (typeof this.id === 'string') {
return this.id;
}
if (typeof this._localId === 'string') {
return this._localId;
}
const localId = 'local' + String(localCount++);
this._localId = localId;
return localId;
}
TO
_getId()
/*: string*/
{
if (typeof this.id === 'string') {
return this.id;
}
if (typeof this._localId === 'string') {
return this._localId;
}
const localId = 'local' + this._uuidv4();
this._localId = localId;
return localId;
}
_uuidv4() {
return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, c =>
(c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
);
}
and it started working great for me.
Before this change, one lagging issue I was seeing was that even fixing the localID as I outlined in my original post above, on restart the objects could get overwritten with the localID getting reset. This change to using a UUID just now seems to have fixed my issue with local pinned objects in active memory and when the app is restarted.
@wfilleman You mentioned a second issue with commitServerChanges. Can you provide a test case similar to https://github.com/parse-community/Parse-SDK-JS/issues/899#issuecomment-540882389 or sample code to replicate it?
@dplewis,
The code as-is:
export function commitServerChanges(serverData: AttributeMap, objectCache: ObjectCache, changes: AttributeMap) {
for (const attr in changes) {
const val = changes[attr];
serverData[attr] = val;
if (val &&
typeof val === 'object' &&
!(val instanceof ParseObject) &&
!(val instanceof ParseFile) &&
!(val instanceof ParseRelation)
) {
const json = encode(val, false, true);
objectCache[attr] = JSON.stringify(json);
}
}
}
This doesn't save the val into the objectCache if it's not an object. So, if you assign string or bool to values on the object attributes, these are saved to the serverData object which works great to get it back to the ParseServer, but the local cache isn't getting the same data for some reason. This breaks the local datastore pin since the local data cache won't have these values in cache.
To reproduce, create a parse object and assign it strings or bools to the attributes and then pin the object only. The object cache for this object will not have these values saved to the cache. When the app restarts or the cache is referenced again, you'll lose your saved local pinned data.
@wfilleman objectCache is only used for checking dirty objects. It caches objects.
This isn't an issue. Unless you have an issue with dirty objects.
@dplewis If I use the published commitServerChanges as-is I get some really odd behavior when only pinning local objects. By odd, I mean that the data in these objects aren't getting saved reliably to and back from the local data store. The only way I can get reliable save behavior is if I cache vals that are strings and bools as well as objects. I admit I don't know what all is happening here as to why that is, but I know for sure I have very obvious problems with local pinning only if I don't cache my attribute strings and bools.
@wfilleman Can you open a Pull Request? If you can write a failing test case we can identify where the problem is.
You can copy one of the test cases here
If you need help look at the Contributing Guide.
@dplewis Yes, I can take a look at putting that together, but let me ask this first: In the test cases I see that .save() or .saveAll() is called which I strongly suspect is why the test cases aren't seeing this issue. As I outlined above, I can't call .save() on my local pinned objects since my users are requesting to be local network only (no cloud parse server) but many have an internet connection. In my testing, calling .save() will write back to the configured ParseServer which I don't want in a subset of cases (sensitive data that should be locally stored only for example).
How should I save pinned objects without getting ParseServer involved?
Just call object.pin without saving. Look here
@dplewis Perfect, thank you. I will investigate why I'm seeing different behavior and open a new issue/PR.
Just to close out this issue for anyone reading this thread: I was able to get locally pinning objects to work by using this localID fix as UUID in the 2.8.0 release as well as calling Parse.Object.disableSingleInstance();
There are side-effects if your codebase needs to support both objects from ParseServer and local-only without a server backing these local models. Specifically, updated objects from LiveQuery ParseServer are now separate objects and won't update the original object if your codebase is holding onto the originals.
Many thanks to @dplewis for sticking with this issue and offering insight.