This repository has been archived by the owner on Jan 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
gc.js
210 lines (178 loc) · 4.92 KB
/
gc.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
import { FinalizationRegistryCallbackError } from './errors.js'
import console from './console.js'
import { noop } from './util.js'
if (typeof FinalizationRegistry === 'undefined') {
console.warn(
'FinalizationRegistry is not implemented in this environment. ' +
'gc.ref() will have no effect.'
)
}
export const finalizers = new WeakMap()
export const kFinalizer = Symbol.for('gc.finalizer')
export const finalizer = kFinalizer
export const pool = new Set()
/**
* Static registry for objects to clean up underlying resources when they
* are gc'd by the environment. There is no guarantee that the `finalizer()`
* is called at any time.
*/
export const registry = new FinalizationRegistry(finalizationRegistryCallback)
/**
* Default exports which also acts a retained value to persist bound
* `Finalizer#handle()` functions from being gc'd before the
* `FinalizationRegistry` callback is called because `heldValue` must be
* strongly held (retained) in order for the callback to be called.
*/
export const gc = Object.freeze(Object.create(null, Object.getOwnPropertyDescriptors({
ref,
pool,
unref,
retain,
release,
registry,
finalize,
finalizer,
finalizers,
get refs () { return pool.size }
})))
// `gc` is also the default export
export default gc
/**
* Internal `FinalizationRegistry` callback.
* @private
* @param {Finalizer} finalizer
*/
async function finalizationRegistryCallback (finalizer) {
if (typeof finalizer.handle === 'function') {
try {
await finalizer.handle(...finalizer.args)
} catch (e) {
const err = new FinalizationRegistryCallbackError(e.message, {
cause: e
})
if (typeof Error.captureStackTrace === 'function') {
Error.captureStackTrace(err, finalizationRegistryCallback)
}
console.warn(err.name, err.message, err.stack, err.cause)
}
}
for (const weakRef of pool) {
if (weakRef instanceof WeakRef) {
const ref = weakRef.deref()
if (ref && ref !== finalizer) {
continue
}
}
pool.delete(weakRef)
}
finalizer = undefined
}
/**
* A container for strongly (retain) referenced finalizer function
* with arguments weakly referenced to an object that will be
* garbage collected.
*/
export class Finalizer {
/**
* Creates a `Finalizer` from input.
*/
static from (handler) {
if (typeof handler === 'function') {
return new this([], handler)
}
let { handle, args } = handler
if (typeof handle !== 'function') {
handle = noop
}
if (!Array.isArray(args)) {
args = []
}
return new this(args, handle)
}
/**
* `Finalizer` class constructor.
* @private
* @param {array} args
* @param {function} handle
*/
constructor (args, handle) {
this.args = args
this.handle = handle.bind(gc)
}
}
/**
* Track `object` ref to call `Symbol.for('gc.finalize')` method when
* environment garbage collects object.
* @param {object} object
* @return {boolean}
*/
export async function ref (object, ...args) {
if (object && typeof object[kFinalizer] === 'function') {
const finalizer = Finalizer.from(await object[kFinalizer](...args))
const weakRef = new WeakRef(finalizer)
finalizers.set(object, weakRef)
pool.add(weakRef)
registry.register(object, finalizer, object)
}
return finalizers.has(object)
}
/**
* Stop tracking `object` ref to call `Symbol.for('gc.finalize')` method when
* environment garbage collects object.
* @param {object} object
* @return {boolean}
*/
export function unref (object) {
if (!object || typeof object !== 'object') {
return false
}
if (typeof object[kFinalizer] === 'function' && finalizers.has(object)) {
const weakRef = finalizers.get(object)
if (weakRef) {
pool.delete(weakRef)
}
finalizers.delete(object)
registry.unregister(object)
return true
}
return false
}
/**
* An alias for `unref()`
* @param {object} object}
* @return {boolean}
*/
export function retain (object) {
return unref(object)
}
/**
* Call finalize on `object` for `gc.finalizer` implementation.
* @param {object} object]
* @return {Promise<boolean>}
*/
export async function finalize (object, ...args) {
const finalizer = finalizers.get(object)?.deref()
registry.unregister(object)
try {
if (finalizer instanceof Finalizer && await unref(object)) {
await finalizationRegistryCallback(finalizer)
} else {
const finalizer = Finalizer.from(await object[kFinalizer](...args))
await finalizationRegistryCallback(finalizer)
}
return true
} catch (err) {
return false
}
}
/**
* Calls all pending finalization handlers forcefully. This function
* may have unintended consequences as objects be considered finalized
* and still strongly held (retained) somewhere.
*/
export async function release () {
for (const weakRef of pool) {
await finalizationRegistryCallback(weakRef?.deref?.())
pool.delete(weakRef)
}
}