summaryrefslogtreecommitdiffstats
path: root/devtools/shared/protocol/types.js
blob: 31c71276ea8a3489afc92062004484653596af16 (plain)
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

var { Actor } = require("resource://devtools/shared/protocol/Actor.js");
var {
  lazyLoadSpec,
  lazyLoadFront,
} = require("resource://devtools/shared/specs/index.js");

/**
 * Types: named marshallers/demarshallers.
 *
 * Types provide a 'write' function that takes a js representation and
 * returns a protocol representation, and a "read" function that
 * takes a protocol representation and returns a js representation.
 *
 * The read and write methods are also passed a context object that
 * represent the actor or front requesting the translation.
 *
 * Types are referred to with a typestring.  Basic types are
 * registered by name using addType, and more complex types can
 * be generated by adding detail to the type name.
 */

var types = Object.create(null);
exports.types = types;

var registeredTypes = (types.registeredTypes = new Map());

exports.registeredTypes = registeredTypes;

/**
 * Return the type object associated with a given typestring.
 * If passed a type object, it will be returned unchanged.
 *
 * Types can be registered with addType, or can be created on
 * the fly with typestrings.  Examples:
 *
 *   boolean
 *   threadActor
 *   threadActor#detail
 *   array:threadActor
 *   array:array:threadActor#detail
 *
 * @param [typestring|type] type
 *    Either a typestring naming a type or a type object.
 *
 * @returns a type object.
 */
types.getType = function (type) {
  if (!type) {
    return types.Primitive;
  }

  if (typeof type !== "string") {
    return type;
  }

  // If already registered, we're done here.
  let reg = registeredTypes.get(type);
  if (reg) {
    return reg;
  }

  // Try to lazy load the spec, if not already loaded.
  if (lazyLoadSpec(type)) {
    // If a spec module was lazy loaded, it will synchronously call
    // generateActorSpec, and set the type in `registeredTypes`.
    reg = registeredTypes.get(type);
    if (reg) {
      return reg;
    }
  }

  // New type, see if it's a collection type:
  const sep = type.indexOf(":");
  if (sep >= 0) {
    const collection = type.substring(0, sep);
    const subtype = types.getType(type.substring(sep + 1));

    if (collection === "array") {
      return types.addArrayType(subtype);
    } else if (collection === "nullable") {
      return types.addNullableType(subtype);
    }

    throw Error("Unknown collection type: " + collection);
  }

  // Not a collection, might be actor detail
  const pieces = type.split("#", 2);
  if (pieces.length > 1) {
    if (pieces[1] != "actorid") {
      throw new Error(
        "Unsupported detail, only support 'actorid', got: " + pieces[1]
      );
    }
    return types.addActorDetail(type, pieces[0], pieces[1]);
  }

  throw Error("Unknown type: " + type);
};

/**
 * Don't allow undefined when writing primitive types to packets.  If
 * you want to allow undefined, use a nullable type.
 */
function identityWrite(v) {
  if (v === undefined) {
    throw Error("undefined passed where a value is required");
  }
  // This has to handle iterator->array conversion because arrays of
  // primitive types pass through here.
  if (v && typeof v.next === "function") {
    return [...v];
  }
  return v;
}

/**
 * Add a type to the type system.
 *
 * When registering a type, you can provide `read` and `write` methods.
 *
 * The `read` method will be passed a JS object value from the JSON
 * packet and must return a native representation.  The `write` method will
 * be passed a native representation and should provide a JSONable value.
 *
 * These methods will both be passed a context.  The context is the object
 * performing or servicing the request - on the server side it will be
 * an Actor, on the client side it will be a Front.
 *
 * @param typestring name
 *    Name to register
 * @param object typeObject
 *    An object whose properties will be stored in the type, including
 *    the `read` and `write` methods.
 *
 * @returns a type object that can be used in protocol definitions.
 */
types.addType = function (name, typeObject = {}) {
  if (registeredTypes.has(name)) {
    throw Error("Type '" + name + "' already exists.");
  }

  const type = Object.assign(
    {
      toString() {
        return "[protocol type:" + name + "]";
      },
      name,
      primitive: !(typeObject.read || typeObject.write),
      read: identityWrite,
      write: identityWrite,
    },
    typeObject
  );

  registeredTypes.set(name, type);

  return type;
};

/**
 * Remove a type previously registered with the system.
 * Primarily useful for types registered by addons.
 */
types.removeType = function (name) {
  // This type may still be referenced by other types, make sure
  // those references don't work.
  const type = registeredTypes.get(name);

  type.name = "DEFUNCT:" + name;
  type.category = "defunct";
  type.primitive = false;
  type.read = type.write = function () {
    throw new Error("Using defunct type: " + name);
  };

  registeredTypes.delete(name);
};

/**
 * Add an array type to the type system.
 *
 * getType() will call this function if provided an "array:<type>"
 * typestring.
 *
 * @param type subtype
 *    The subtype to be held by the array.
 */
types.addArrayType = function (subtype) {
  subtype = types.getType(subtype);

  const name = "array:" + subtype.name;

  // Arrays of primitive types are primitive types themselves.
  if (subtype.primitive) {
    return types.addType(name);
  }
  return types.addType(name, {
    category: "array",
    read: (v, ctx) => {
      if (v && typeof v.next === "function") {
        v = [...v];
      }
      return v.map(i => subtype.read(i, ctx));
    },
    write: (v, ctx) => {
      if (v && typeof v.next === "function") {
        v = [...v];
      }
      return v.map(i => subtype.write(i, ctx));
    },
  });
};

/**
 * Add a dict type to the type system.  This allows you to serialize
 * a JS object that contains non-primitive subtypes.
 *
 * Properties of the value that aren't included in the specializations
 * will be serialized as primitive values.
 *
 * @param object specializations
 *    A dict of property names => type
 */
types.addDictType = function (name, specializations) {
  const specTypes = {};
  for (const prop in specializations) {
    try {
      specTypes[prop] = types.getType(specializations[prop]);
    } catch (e) {
      // Types may not be defined yet. Sometimes, we define the type *after* using it, but
      // also, we have cyclic definitions on types. So lazily load them when they are not
      // immediately available.
      loader.lazyGetter(specTypes, prop, () => {
        return types.getType(specializations[prop]);
      });
    }
  }
  return types.addType(name, {
    category: "dict",
    specializations,
    read: (v, ctx) => {
      const ret = {};
      for (const prop in v) {
        if (prop in specTypes) {
          ret[prop] = specTypes[prop].read(v[prop], ctx);
        } else {
          ret[prop] = v[prop];
        }
      }
      return ret;
    },

    write: (v, ctx) => {
      const ret = {};
      for (const prop in v) {
        if (prop in specTypes) {
          ret[prop] = specTypes[prop].write(v[prop], ctx);
        } else {
          ret[prop] = v[prop];
        }
      }
      return ret;
    },
  });
};

/**
 * Register an actor type with the type system.
 *
 * Types are marshalled differently when communicating server->client
 * than they are when communicating client->server.  The server needs
 * to provide useful information to the client, so uses the actor's
 * `form` method to get a json representation of the actor.  When
 * making a request from the client we only need the actor ID string.
 *
 * This function can be called before the associated actor has been
 * constructed, but the read and write methods won't work until
 * the associated addActorImpl or addActorFront methods have been
 * called during actor/front construction.
 *
 * @param string name
 *    The typestring to register.
 */
types.addActorType = function (name) {
  // We call addActorType from:
  //   FrontClassWithSpec when registering front synchronously,
  //   generateActorSpec when defining specs,
  //   specs modules to register actor type early to use them in other types
  if (registeredTypes.has(name)) {
    return registeredTypes.get(name);
  }
  const type = types.addType(name, {
    _actor: true,
    category: "actor",
    read: (v, ctx, detail) => {
      // If we're reading a request on the server side, just
      // find the actor registered with this actorID.
      if (ctx instanceof Actor) {
        return ctx.conn.getActor(v);
      }

      // Reading a response on the client side, check for an
      // existing front on the connection, and create the front
      // if it isn't found.
      const actorID = typeof v === "string" ? v : v.actor;
      // `ctx.conn` is a DevToolsClient
      let front = ctx.conn.getFrontByID(actorID);

      // When the type `${name}#actorid` is used, `v` is a string refering to the
      // actor ID. We cannot read form information in this case and the actorID was
      // already set when creating the front, so no need to do anything.
      let form = null;
      if (detail != "actorid") {
        form = identityWrite(v);
      }

      if (!front) {
        // If front isn't instantiated yet, create one.
        // Try lazy loading front if not already loaded.
        // The front module will synchronously call `FrontClassWithSpec` and
        // augment `type` with the `frontClass` attribute.
        if (!type.frontClass) {
          lazyLoadFront(name);
        }

        const parentFront = ctx.marshallPool();
        const targetFront = parentFront.isTargetFront
          ? parentFront
          : parentFront.targetFront;

        // Use intermediate Class variable to please eslint requiring
        // a capital letter for all constructors.
        const Class = type.frontClass;
        front = new Class(ctx.conn, targetFront, parentFront);
        front.actorID = actorID;

        parentFront.manage(front, form, ctx);
      } else if (form) {
        front.form(form, ctx);
      }

      return front;
    },
    write: (v, ctx, detail) => {
      // If returning a response from the server side, make sure
      // the actor is added to a parent object and return its form.
      if (v instanceof Actor) {
        if (v.isDestroyed()) {
          throw new Error(
            `Attempted to write a response containing a destroyed actor`
          );
        }
        if (!v.actorID) {
          ctx.marshallPool().manage(v);
        }
        if (detail == "actorid") {
          return v.actorID;
        }
        return identityWrite(v.form(detail));
      }

      // Writing a request from the client side, just send the actor id.
      return v.actorID;
    },
  });
  return type;
};

types.addPolymorphicType = function (name, subtypes) {
  // Assert that all subtypes are actors, as the marshalling implementation depends on that.
  for (const subTypeName of subtypes) {
    const subtype = types.getType(subTypeName);
    if (subtype.category != "actor") {
      throw new Error(
        `In polymorphic type '${subtypes.join(
          ","
        )}', the type '${subTypeName}' isn't an actor`
      );
    }
  }

  return types.addType(name, {
    category: "polymorphic",
    read: (value, ctx) => {
      // `value` is either a string which is an Actor ID or a form object
      // where `actor` is an actor ID
      const actorID = typeof value === "string" ? value : value.actor;
      if (!actorID) {
        throw new Error(
          `Was expecting one of these actors '${subtypes}' but instead got value: '${value}'`
        );
      }

      // Extract the typeName out of the actor ID, which should be composed like this
      // ${DevToolsServerConnectionPrefix}.${typeName}${Number}
      const typeName = actorID.match(/\.([a-zA-Z]+)\d+$/)[1];
      if (!subtypes.includes(typeName)) {
        throw new Error(
          `Was expecting one of these actors '${subtypes}' but instead got an actor of type: '${typeName}'`
        );
      }

      const subtype = types.getType(typeName);
      return subtype.read(value, ctx);
    },
    write: (value, ctx) => {
      if (!value) {
        throw new Error(
          `Was expecting one of these actors '${subtypes}' but instead got an empty value.`
        );
      }
      // value is either an `Actor` or a `Front` and both classes exposes a `typeName`
      const typeName = value.typeName;
      if (!typeName) {
        throw new Error(
          `Was expecting one of these actors '${subtypes}' but instead got value: '${value}'. Did you pass a form instead of an Actor?`
        );
      }

      if (!subtypes.includes(typeName)) {
        throw new Error(
          `Was expecting one of these actors '${subtypes}' but instead got an actor of type: '${typeName}'`
        );
      }

      const subtype = types.getType(typeName);
      return subtype.write(value, ctx);
    },
  });
};
types.addNullableType = function (subtype) {
  subtype = types.getType(subtype);
  return types.addType("nullable:" + subtype.name, {
    category: "nullable",
    read: (value, ctx) => {
      if (value == null) {
        return value;
      }
      return subtype.read(value, ctx);
    },
    write: (value, ctx) => {
      if (value == null) {
        return value;
      }
      return subtype.write(value, ctx);
    },
  });
};

/**
 * Register an actor detail type.  This is just like an actor type, but
 * will pass a detail hint to the actor's form method during serialization/
 * deserialization.
 *
 * This is called by getType() when passed an 'actorType#detail' string.
 *
 * @param string name
 *   The typestring to register this type as.
 * @param type actorType
 *   The actor type you'll be detailing.
 * @param string detail
 *   The detail to pass.
 */
types.addActorDetail = function (name, actorType, detail) {
  actorType = types.getType(actorType);
  if (!actorType._actor) {
    throw Error(
      `Details only apply to actor types, tried to add detail '${detail}' ` +
        `to ${actorType.name}`
    );
  }
  return types.addType(name, {
    _actor: true,
    category: "detail",
    read: (v, ctx) => actorType.read(v, ctx, detail),
    write: (v, ctx) => actorType.write(v, ctx, detail),
  });
};

// Add a few named primitive types.
types.Primitive = types.addType("primitive");
types.String = types.addType("string");
types.Number = types.addType("number");
types.Boolean = types.addType("boolean");
types.JSON = types.addType("json");

exports.registerFront = function (cls) {
  const { typeName } = cls.prototype;
  if (!registeredTypes.has(typeName)) {
    types.addActorType(typeName);
  }
  registeredTypes.get(typeName).frontClass = cls;
};

/**
 * Instantiate a front of the given type.
 *
 * @param DevToolsClient client
 *    The DevToolsClient instance to use.
 * @param string typeName
 *    The type name of the front to instantiate. This is defined in its specifiation.
 * @returns Front
 *    The created front.
 */
function createFront(client, typeName, target = null) {
  const type = types.getType(typeName);
  if (!type) {
    throw new Error(`No spec for front type '${typeName}'.`);
  } else if (!type.frontClass) {
    lazyLoadFront(typeName);
  }

  // Use intermediate Class variable to please eslint requiring
  // a capital letter for all constructors.
  const Class = type.frontClass;
  return new Class(client, target, target);
}

/**
 * Instantiate a global (preference, device) or target-scoped (webconsole, inspector)
 * front of the given type by picking its actor ID out of either the target or root
 * front's form.
 *
 * @param DevToolsClient client
 *    The DevToolsClient instance to use.
 * @param string typeName
 *    The type name of the front to instantiate. This is defined in its specifiation.
 * @param json form
 *    If we want to instantiate a global actor's front, this is the root front's form,
 *    otherwise we are instantiating a target-scoped front from the target front's form.
 * @param [Target|null] target
 *    If we are instantiating a target-scoped front, this is a reference to the front's
 *    Target instance, otherwise this is null.
 */
async function getFront(client, typeName, form, target = null) {
  const front = createFront(client, typeName, target);
  const { formAttributeName } = front;
  if (!formAttributeName) {
    throw new Error(`Can't find the form attribute name for ${typeName}`);
  }
  // Retrieve the actor ID from root or target actor's form
  front.actorID = form[formAttributeName];
  if (!front.actorID) {
    throw new Error(
      `Can't find the actor ID for ${typeName} from root or target` +
        ` actor's form.`
    );
  }

  if (!target) {
    await front.manage(front);
  } else {
    await target.manage(front);
  }

  return front;
}
exports.getFront = getFront;

/**
 * Create a RootFront.
 *
 * @param DevToolsClient client
 *    The DevToolsClient instance to use.
 * @param Object packet
 * @returns RootFront
 */
function createRootFront(client, packet) {
  const rootFront = createFront(client, "root");
  rootFront.form(packet);

  // Root Front is a special case, managing itself as it doesn't have any parent.
  // It will register itself to DevToolsClient as a Pool via Front._poolMap.
  rootFront.manage(rootFront);

  return rootFront;
}
exports.createRootFront = createRootFront;