-
Notifications
You must be signed in to change notification settings - Fork 558
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
Indirect weak map and cache #5065
Draft
kraenhansen
wants to merge
11
commits into
main
Choose a base branch
from
kh/bindgen/indirect-weak-map
base: main
Could not load branches
Branch not found: {{ refName }}
Could not load tags
Nothing to show
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
da40e36
Adding an IndirectWeakMap
kraenhansen 13dbbf2
Implemented pruning of the IndirectWeakMap
kraenhansen b086910
Using IndirectWeakMap to map users to apps
kraenhansen 6bbdec8
Adding a comment to the gc util
kraenhansen f2494fa
Renamed to IndirectWeakCache
kraenhansen ae78f43
Made IndirectWeakMap @internal
kraenhansen 46214e9
Fixed typo in docs
kraenhansen 97db9a7
Renamed to getOrCreate and extended IndirectWeakMap
kraenhansen 5c2732a
Less abbreviated names
kraenhansen 0631f45
Updated names again.
kraenhansen 8bb28de
Fixed the implementation
kraenhansen File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
//////////////////////////////////////////////////////////////////////////// | ||
// | ||
// Copyright 2022 Realm Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
//////////////////////////////////////////////////////////////////////////// | ||
|
||
import { IdGetter, IndirectWeakMap } from "./internal"; | ||
|
||
/** | ||
* A cache of objects (the value) which can either be constructed on demand or retrieved from cache. | ||
* The cache is considered weak as it extends the `IndirectWeakMap` to store its values, making them available | ||
* for garbage collection. | ||
* @internal | ||
*/ | ||
export class IndirectWeakCache< | ||
K extends object, | ||
V extends object, | ||
Args extends unknown[], | ||
Id = unknown, | ||
> extends IndirectWeakMap<K, V, Id> { | ||
constructor(private construct: { new (...args: Args): V }, getId: IdGetter<K, Id>) { | ||
super(getId); | ||
} | ||
/** | ||
* Get an existing value from the cache or construct and store one in case of a miss. | ||
* @param key Object passed to the getId function provided at construction of the cache. | ||
* @param args An optional array of constructor arguments can be passed as well, which will be used in case of a cache miss | ||
* to construct and store a new value object. | ||
* @returns An existing or new value. | ||
* @throws If `args` are not supplied and no object existed in the cache. | ||
*/ | ||
getOrCreate(key: K, args?: Args) { | ||
const existing = this.get(key); | ||
if (existing) { | ||
return existing; | ||
} else if (args) { | ||
const result = new this.construct(...args); | ||
this.set(key, result); | ||
return result; | ||
} else { | ||
throw new Error("Needed to create an object, but no args were supplied"); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,74 @@ | ||
//////////////////////////////////////////////////////////////////////////// | ||
// | ||
// Copyright 2022 Realm Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
//////////////////////////////////////////////////////////////////////////// | ||
|
||
/** @internal */ | ||
export type IdGetter<K, Id> = (key: K) => Id; | ||
|
||
/** | ||
* A map from some type of object (the key) into another type of object (the value), where a | ||
* function (the `getId` function supplied at construction) is called to derive an id of the key, | ||
* which is used when looking up the value. This makes it possible for multiple different key | ||
* objects to get the same value object. This is subtly different from a traditional hash map, | ||
* the id is the only value used as basis for key equality, meaning two different key objects could | ||
* map to the same value, as long as they derive to the same id. | ||
* This property is what is considered "indirect" about the map. | ||
* The map is considered weak in the sense that values are wrapped in a `WeakRef` before being | ||
* inserted in the underling map. A value is also registered with a finalization registry, ensuring | ||
* that their entry in the underlying map is removed when they get garbage collected, | ||
* in an effort to make the entire `IndirectWeakMap` avoid leaks. | ||
* @internal | ||
*/ | ||
export class IndirectWeakMap<K extends object, V extends object, Id> implements WeakMap<K, V> { | ||
[Symbol.toStringTag] = "IndirectWeakMap"; | ||
|
||
private registry = new FinalizationRegistry<Id>((hash) => { | ||
this.values.delete(hash); | ||
}); | ||
|
||
constructor(private getId: IdGetter<K, Id>, private values: Map<Id, WeakRef<V>> = new Map()) {} | ||
|
||
set(key: K, value: V): this { | ||
const id = this.getId(key); | ||
const ref = new WeakRef(value); | ||
// Unregister the finalization registry on value being removed from the map | ||
// to avoid its finalization to prune the new value from the map of values. | ||
const existingRef = this.values.get(id); | ||
if (existingRef) { | ||
this.registry.unregister(existingRef); | ||
} | ||
// Register the new value with the finalization registry, | ||
// to prune its WeakRef from the map of values. | ||
this.registry.register(value, id, ref); | ||
this.values.set(id, ref); | ||
return this; | ||
} | ||
|
||
has(key: K): boolean { | ||
return this.get(key) !== undefined; | ||
} | ||
|
||
get(key: K): V | undefined { | ||
const id = this.getId(key); | ||
return this.values.get(id)?.deref(); | ||
} | ||
|
||
delete(key: K): boolean { | ||
const id = this.getId(key); | ||
return this.values.delete(id); | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,62 @@ | ||
//////////////////////////////////////////////////////////////////////////// | ||
// | ||
// Copyright 2022 Realm Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
//////////////////////////////////////////////////////////////////////////// | ||
|
||
import { expect } from "chai"; | ||
|
||
import { gc } from "./utils"; | ||
|
||
import { IndirectWeakCache } from "../IndirectWeakCache"; | ||
|
||
describe("IndirectWeakCache", () => { | ||
it("constructs, gets and forgets values", async () => { | ||
class Internal { | ||
constructor(public $addr: bigint) {} | ||
} | ||
class External { | ||
constructor(public foo: string) {} | ||
} | ||
|
||
const int1 = new Internal(1n); | ||
const int1b = new Internal(1n); | ||
|
||
const cache = new IndirectWeakCache(External, ({ $addr }: Internal) => $addr); | ||
const objs: Record<number, External> = {}; | ||
objs[0] = cache.getOrCreate(int1, ["bar"]); | ||
expect(objs[0].foo).equals("bar"); | ||
// Getting again with another key sharing the $addr should return the same object | ||
objs[1] = cache.getOrCreate(int1b, ["baz"]); | ||
expect(objs[1]).equals(objs[0]); | ||
// And it shouldn't update the object | ||
expect(objs[1].foo).equals("bar"); | ||
// Getting again without providing constructor args should return the same object | ||
objs[2] = cache.getOrCreate(int1); | ||
expect(objs[2]).equals(objs[0]); | ||
|
||
// Forgetting the previously returned values, should make the cache forget the original object | ||
delete objs[0]; | ||
delete objs[1]; | ||
delete objs[2]; | ||
await gc(); | ||
await gc(); | ||
|
||
// Now that the object is pruned from cache, we need to supply constructor arguments when getting it | ||
expect(() => { | ||
cache.getOrCreate(int1); | ||
}).throws("Needed to create an object, but no args were supplied"); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,84 @@ | ||
//////////////////////////////////////////////////////////////////////////// | ||
// | ||
// Copyright 2022 Realm Inc. | ||
// | ||
// Licensed under the Apache License, Version 2.0 (the "License"); | ||
// you may not use this file except in compliance with the License. | ||
// You may obtain a copy of the License at | ||
// | ||
// http://www.apache.org/licenses/LICENSE-2.0 | ||
// | ||
// Unless required by applicable law or agreed to in writing, software | ||
// distributed under the License is distributed on an "AS IS" BASIS, | ||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
// See the License for the specific language governing permissions and | ||
// limitations under the License. | ||
// | ||
//////////////////////////////////////////////////////////////////////////// | ||
|
||
import { expect } from "chai"; | ||
|
||
import { IndirectWeakMap } from "../IndirectWeakMap"; | ||
import { gc } from "./utils"; | ||
|
||
type TestKey = { hash: number }; | ||
type TestValue = { message: string }; | ||
|
||
describe("IndirectWeakMap", () => { | ||
it("is possible to test WeakRef", async () => { | ||
const ref = new WeakRef({ foo: "bar" }); | ||
await gc(); | ||
expect(ref.deref()).equals(undefined); | ||
}); | ||
|
||
it("stores, retrieves and forgets values", async () => { | ||
const internalMap = new Map<number, WeakRef<TestValue>>(); | ||
const map = new IndirectWeakMap<TestKey, TestValue, number>((k) => k.hash, internalMap); | ||
|
||
const key1: TestKey = { hash: 1 }; | ||
const key2: TestKey = { hash: 2 }; | ||
const values: TestValue[] = [{ message: "A" }, { message: "B" }, { message: "C" }]; | ||
map.set(key1, values[0]); | ||
map.set(key2, values[1]); | ||
expect(map.get(key1)).equals(values[0]); | ||
expect(map.get(key2)).equals(values[1]); | ||
expect(map.has(key1)).equals(true); | ||
expect(internalMap.size).equals(2); | ||
|
||
// Forget and garbage collect a value | ||
delete values[0]; | ||
await gc(); | ||
// We need two gc cycles for the finalization registry to kick in | ||
await gc(); | ||
|
||
expect(map.get(key1)).equals(undefined); | ||
expect(map.get(key2)).equals(values[1]); | ||
expect(map.has(key1)).equals(false); | ||
expect(map.has(key2)).equals(true); | ||
expect(internalMap.size).equals(1); | ||
|
||
// Try getting a value for a different key object with the same hash | ||
const key2b: TestKey = { hash: 2 }; | ||
expect(map.get(key2b)).equals(values[1]); | ||
|
||
// Try overriding an existing value | ||
map.set(key2, values[2]); | ||
expect(map.get(key2)).equals(values[2]); | ||
|
||
// Forgetting the previous value shouldn't prune the internal map | ||
delete values[1]; | ||
await gc(); | ||
// We need two gc cycles for the finalization registry to kick in | ||
await gc(); | ||
|
||
expect(map.get(key2)).equals(values[2]); | ||
|
||
// Forgetting the last value should prune the internal map entirely | ||
delete values[2]; | ||
await gc(); | ||
// We need two gc cycles for the finalization registry to kick in | ||
await gc(); | ||
|
||
expect(internalMap.size).equals(0); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In my opinion, we should start naming our generics. I always have to read the implementation to deduce what these letters actually mean. Could be as simple as:
Thoughts?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I agree .. ol' habits stick around.
I pushed a commit with some less abbreviated names 🙂
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Meh. I think K and V are pretty classic abbreviations for Key and Value. And I don't think the Type suffix adds any value, both because they are capitalized, and because types are the only thing that TS supports as generic arguments (even things that look "valuey" like
true
and"hello"
are promoted to "literal types" and are still considered types).I agree that
Args
andHash
are good names though. But we don't need to go all Java Enterprise Edition on all of our names.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Time to flip a 🪙 regarding
Key
vsK
andValue
vsV
?I don't feel strong either way.
As much as I like a good name, please also read / review the other code too 😉
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I mean, i'm not gonna die on this hill, but i've always felt being more explicit is better. As long as we don't start using T, K, V for anything else that Type, Key and Value, i'm fine with it. Just be explicit where it matters.