-
Notifications
You must be signed in to change notification settings - Fork 208
/
callback.js
315 lines (297 loc) · 9.25 KB
/
callback.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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
// @ts-check
import { Fail, makeError, q } from '@endo/errors';
import { E } from '@endo/far';
import { isObject, isPassableSymbol } from '@endo/marshal';
import { getInterfaceMethodKeys } from '@endo/patterns';
/** @import {ERef} from '@endo/far' */
/** @import {Callback, SyncCallback} from './types.js' */
const { fromEntries } = Object;
const { ownKeys: rawOwnKeys } = Reflect;
const ownKeys =
/** @type {<T extends PropertyKey>(obj: { [K in T]?: unknown }) => T[]} */ (
rawOwnKeys
);
/**
* @template {import('@endo/exo').Methods} T
* @typedef {(
* ...args: Parameters<ReturnType<prepareAttenuator>>
* ) => import('@endo/exo').Farable<T>} MakeAttenuator
*/
/**
* @param {unknown} key
* @returns {key is PropertyKey} FIXME: should be just `PropertyKey` but TS
* complains it can't be used as an index type.
*/
const isPropertyKey = key => {
switch (typeof key) {
case 'string':
case 'number':
case 'symbol':
return true;
default:
return false;
}
};
/**
* Synchronously call a callback.
*
* @template {(...args: any[]) => any} I
* @param {SyncCallback<I>} callback
* @param {Parameters<I>} args
* @returns {ReturnType<I>}
*/
export const callSync = (callback, ...args) => {
const { target, methodName, bound } = callback;
if (methodName === undefined) {
return target(...bound, ...args);
}
return target[methodName](...bound, ...args);
};
harden(callSync);
/**
* Eventual send to a callback.
*
* @template {(...args: any[]) => any} I
* @param {Callback<I>} callback
* @param {Parameters<I>} args
* @returns {Promise<Awaited<ReturnType<I>>>}
*/
export const callE = (callback, ...args) => {
const { target, methodName, bound } = callback;
if (methodName === undefined) {
return E(target)(...bound, ...args);
}
return E(target)[methodName](...bound, ...args);
};
harden(callE);
/**
* Create a callback from a near function.
*
* @template {(...args: any[]) => any} I
* @template {(...args: [...B, ...Parameters<I>]) => ReturnType<I>} [T=I]
* @template {any[]} [B=[]]
* @param {T} target
* @param {B} bound
* @returns {SyncCallback<I>}
*/
export const makeSyncFunctionCallback = (target, ...bound) => {
typeof target === 'function' ||
Fail`sync function callback target must be a function: ${target}`;
/** @type {unknown} */
const cb = harden({ target, bound, isSync: true });
return /** @type {SyncCallback<I>} */ (cb);
};
harden(makeSyncFunctionCallback);
/**
* Create a callback from a potentially far function.
*
* @template {(...args: any[]) => any} I
* @template {ERef<(...args: [...B, ...Parameters<I>]) => ReturnType<I>>} [T=ERef<I>]
* @template {any[]} [B=[]]
* @param {T} target
* @param {B} bound
* @returns {Callback<I>}
*/
export const makeFunctionCallback = (target, ...bound) => {
isObject(target) ||
Fail`function callback target must be a function presence: ${target}`;
/** @type {unknown} */
const cb = harden({ target, bound });
return /** @type {Callback<I>} */ (cb);
};
harden(makeFunctionCallback);
/**
* Create a callback from a near method.
*
* @template {(...args: any[]) => any} I
* @template {PropertyKey} P
* @template {{
* [x in P]: (...args: [...B, ...Parameters<I>]) => ReturnType<I>;
* }} [T={ [x in P]: I }]
* @template {any[]} [B=[]]
* @param {T} target
* @param {P} methodName
* @param {B} bound
* @returns {SyncCallback<I>}
*/
export const makeSyncMethodCallback = (target, methodName, ...bound) => {
isObject(target) ||
Fail`sync method callback target must be an object: ${target}`;
typeof methodName === 'string' ||
isPassableSymbol(methodName) ||
Fail`method name must be a string or passable symbol: ${methodName}`;
/** @type {unknown} */
const cb = harden({ target, methodName, bound, isSync: true });
return /** @type {SyncCallback<I>} */ (cb);
};
harden(makeSyncMethodCallback);
/**
* Create a callback from a potentially far method.
*
* @template {(...args: any[]) => any} I
* @template {PropertyKey} P
* @template {ERef<{
* [x in P]: (...args: [...B, ...Parameters<I>]) => ReturnType<I>;
* }>} [T=ERef<{ [x in P]: I }>]
* @template {any[]} [B=[]]
* @param {T} target
* @param {P} methodName
* @param {B} bound
* @returns {Callback<I>}
*/
export const makeMethodCallback = (target, methodName, ...bound) => {
isObject(target) || Fail`method callback target must be an object: ${target}`;
typeof methodName === 'string' ||
isPassableSymbol(methodName) ||
Fail`method name must be a string or passable symbol: ${methodName}`;
/** @type {unknown} */
const cb = harden({ target, methodName, bound });
return /** @type {Callback<I>} */ (cb);
};
harden(makeMethodCallback);
/**
* @param {any} callback
* @returns {callback is Callback<any>}
*/
export const isCallback = callback => {
if (!isObject(callback)) {
return false;
}
const { target, methodName, bound } = callback;
return (
isObject(target) &&
(methodName === undefined ||
typeof methodName === 'string' ||
isPassableSymbol(methodName)) &&
Array.isArray(bound)
);
};
harden(isCallback);
/**
* Prepare an attenuator class whose methods can be redirected via callbacks.
*
* @template {PropertyKey} M
* @param {import('@agoric/base-zone').Zone} zone The zone in which to allocate
* attenuators.
* @param {M[]} methodNames Methods to forward.
* @param {object} opts
* @param {import('@endo/patterns').InterfaceGuard<{
* [K in M]: import('@endo/patterns').MethodGuard;
* }>} [opts.interfaceGuard]
* An interface guard for the new attenuator.
* @param {string} [opts.tag] A tag for the new attenuator exoClass.
*/
export const prepareAttenuator = (
zone,
methodNames,
{ interfaceGuard, tag = 'Attenuator' } = {},
) => {
/**
* @typedef {(this: any, ...args: any[]) => any} Method
*
* @typedef {{ [K in M]?: Callback<any> | null }} Overrides
*
* @typedef {{ [K in M]: (this: any, ...args: any[]) => any }} Methods
*/
const methods = /** @type {Methods} */ (
fromEntries(
methodNames.map(key => {
// Only allow the `PropertyKey` type for the target method key.
if (!isPropertyKey(key)) {
throw Fail`key ${q(key)} is not a PropertyKey`;
}
const m = /** @type {Methods} */ ({
// Explicitly use concise method syntax to preserve `this` but prevent
// constructor behavior.
/** @type {Method} */
[key](...args) {
// Support both synchronous and async callbacks.
const cb = this.state.cbs[key];
if (!cb) {
const err = makeError(`unimplemented ${q(tag)} method ${q(key)}`);
if (this.state.isSync) {
throw err;
}
return Promise.reject(err);
}
if (cb.isSync) {
return callSync(cb, ...args);
}
return callE(cb, ...args);
},
})[key];
return /** @type {const} */ ([key, m]);
}),
)
);
/**
* Create an exo object whose behavior is composed from a default target
* and/or individual method override callbacks.
*
* @param {object} opts
* @param {unknown} [opts.target] The target for any methods that weren't
* specified in `opts.overrides`.
* @param {boolean} [opts.isSync=false] Whether the target should be treated
* as synchronously available.
* @param {Overrides} [opts.overrides] Set individual callbacks for methods
* (whose names must be defined in the `prepareAttenuator` or
* `prepareGuardedAttenuator` call). Nullish overrides mean to throw.
*/
const makeAttenuator = zone.exoClass(
tag,
interfaceGuard,
/**
* @param {object} opts
* @param {any} [opts.target]
* @param {boolean} [opts.isSync]
* @param {Overrides} [opts.overrides]
*/
({
target = null,
isSync = false,
overrides = /** @type {Overrides} */ ({}),
}) => {
const cbs = /** @type {Overrides} */ ({});
const remaining = new Set(methodNames);
for (const key of ownKeys(overrides)) {
remaining.has(key) ||
Fail`${q(tag)} overrides[${q(key)}] not allowed by methodNames`;
remaining.delete(key);
const cb = overrides[key];
cb == null ||
isCallback(cb) ||
Fail`${q(tag)} overrides[${q(key)}] is not a callback; got ${cb}`;
cbs[key] = cb;
}
for (const key of remaining) {
if (isSync) {
cbs[key] = makeSyncMethodCallback(target, key);
} else {
cbs[key] = makeMethodCallback(target, key);
}
}
return harden({ cbs, isSync });
},
/** @type {Methods} */ (methods),
);
return makeAttenuator;
};
harden(prepareAttenuator);
/**
* Prepare an attenuator whose methodNames are derived from the interfaceGuard.
*
* @template {import('@endo/patterns').InterfaceGuard} G
* @param {import('@agoric/base-zone').Zone} zone
* @param {G} interfaceGuard
* @param {object} [opts]
* @param {string} [opts.tag]
*/
export const prepareGuardedAttenuator = (zone, interfaceGuard, opts = {}) => {
const methodNames = getInterfaceMethodKeys(interfaceGuard);
const makeAttenuator = prepareAttenuator(zone, methodNames, {
...opts,
interfaceGuard,
});
return /** @type {MakeAttenuator<any>} */ (makeAttenuator);
};
harden(prepareGuardedAttenuator);