protocol.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518
  1. /* This Source Code Form is subject to the terms of the Mozilla Public
  2. * License, v. 2.0. If a copy of the MPL was not distributed with this
  3. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  4. "use strict";
  5. var promise = require("promise");
  6. var defer = require("devtools/shared/defer");
  7. var {Class} = require("sdk/core/heritage");
  8. var {EventTarget} = require("sdk/event/target");
  9. var events = require("sdk/event/core");
  10. var object = require("sdk/util/object");
  11. var {getStack, callFunctionWithAsyncStack} = require("devtools/shared/platform/stack");
  12. exports.emit = events.emit;
  13. /**
  14. * Types: named marshallers/demarshallers.
  15. *
  16. * Types provide a 'write' function that takes a js representation and
  17. * returns a protocol representation, and a "read" function that
  18. * takes a protocol representation and returns a js representation.
  19. *
  20. * The read and write methods are also passed a context object that
  21. * represent the actor or front requesting the translation.
  22. *
  23. * Types are referred to with a typestring. Basic types are
  24. * registered by name using addType, and more complex types can
  25. * be generated by adding detail to the type name.
  26. */
  27. var types = Object.create(null);
  28. exports.types = types;
  29. var registeredTypes = types.registeredTypes = new Map();
  30. var registeredLifetimes = types.registeredLifetimes = new Map();
  31. /**
  32. * Return the type object associated with a given typestring.
  33. * If passed a type object, it will be returned unchanged.
  34. *
  35. * Types can be registered with addType, or can be created on
  36. * the fly with typestrings. Examples:
  37. *
  38. * boolean
  39. * threadActor
  40. * threadActor#detail
  41. * array:threadActor
  42. * array:array:threadActor#detail
  43. *
  44. * @param [typestring|type] type
  45. * Either a typestring naming a type or a type object.
  46. *
  47. * @returns a type object.
  48. */
  49. types.getType = function (type) {
  50. if (!type) {
  51. return types.Primitive;
  52. }
  53. if (typeof (type) !== "string") {
  54. return type;
  55. }
  56. // If already registered, we're done here.
  57. let reg = registeredTypes.get(type);
  58. if (reg) return reg;
  59. // New type, see if it's a collection/lifetime type:
  60. let sep = type.indexOf(":");
  61. if (sep >= 0) {
  62. let collection = type.substring(0, sep);
  63. let subtype = types.getType(type.substring(sep + 1));
  64. if (collection === "array") {
  65. return types.addArrayType(subtype);
  66. } else if (collection === "nullable") {
  67. return types.addNullableType(subtype);
  68. }
  69. if (registeredLifetimes.has(collection)) {
  70. return types.addLifetimeType(collection, subtype);
  71. }
  72. throw Error("Unknown collection type: " + collection);
  73. }
  74. // Not a collection, might be actor detail
  75. let pieces = type.split("#", 2);
  76. if (pieces.length > 1) {
  77. return types.addActorDetail(type, pieces[0], pieces[1]);
  78. }
  79. // Might be a lazily-loaded type
  80. if (type === "longstring") {
  81. require("devtools/shared/specs/string");
  82. return registeredTypes.get("longstring");
  83. }
  84. throw Error("Unknown type: " + type);
  85. };
  86. /**
  87. * Don't allow undefined when writing primitive types to packets. If
  88. * you want to allow undefined, use a nullable type.
  89. */
  90. function identityWrite(v) {
  91. if (v === undefined) {
  92. throw Error("undefined passed where a value is required");
  93. }
  94. // This has to handle iterator->array conversion because arrays of
  95. // primitive types pass through here.
  96. if (v && typeof (v) === "object" && Symbol.iterator in v) {
  97. return [...v];
  98. }
  99. return v;
  100. }
  101. /**
  102. * Add a type to the type system.
  103. *
  104. * When registering a type, you can provide `read` and `write` methods.
  105. *
  106. * The `read` method will be passed a JS object value from the JSON
  107. * packet and must return a native representation. The `write` method will
  108. * be passed a native representation and should provide a JSONable value.
  109. *
  110. * These methods will both be passed a context. The context is the object
  111. * performing or servicing the request - on the server side it will be
  112. * an Actor, on the client side it will be a Front.
  113. *
  114. * @param typestring name
  115. * Name to register
  116. * @param object typeObject
  117. * An object whose properties will be stored in the type, including
  118. * the `read` and `write` methods.
  119. * @param object options
  120. * Can specify `thawed` to prevent the type from being frozen.
  121. *
  122. * @returns a type object that can be used in protocol definitions.
  123. */
  124. types.addType = function (name, typeObject = {}, options = {}) {
  125. if (registeredTypes.has(name)) {
  126. throw Error("Type '" + name + "' already exists.");
  127. }
  128. let type = object.merge({
  129. toString() { return "[protocol type:" + name + "]";},
  130. name: name,
  131. primitive: !(typeObject.read || typeObject.write),
  132. read: identityWrite,
  133. write: identityWrite
  134. }, typeObject);
  135. registeredTypes.set(name, type);
  136. return type;
  137. };
  138. /**
  139. * Remove a type previously registered with the system.
  140. * Primarily useful for types registered by addons.
  141. */
  142. types.removeType = function (name) {
  143. // This type may still be referenced by other types, make sure
  144. // those references don't work.
  145. let type = registeredTypes.get(name);
  146. type.name = "DEFUNCT:" + name;
  147. type.category = "defunct";
  148. type.primitive = false;
  149. type.read = type.write = function () { throw new Error("Using defunct type: " + name); };
  150. registeredTypes.delete(name);
  151. };
  152. /**
  153. * Add an array type to the type system.
  154. *
  155. * getType() will call this function if provided an "array:<type>"
  156. * typestring.
  157. *
  158. * @param type subtype
  159. * The subtype to be held by the array.
  160. */
  161. types.addArrayType = function (subtype) {
  162. subtype = types.getType(subtype);
  163. let name = "array:" + subtype.name;
  164. // Arrays of primitive types are primitive types themselves.
  165. if (subtype.primitive) {
  166. return types.addType(name);
  167. }
  168. return types.addType(name, {
  169. category: "array",
  170. read: (v, ctx) => [...v].map(i => subtype.read(i, ctx)),
  171. write: (v, ctx) => [...v].map(i => subtype.write(i, ctx))
  172. });
  173. };
  174. /**
  175. * Add a dict type to the type system. This allows you to serialize
  176. * a JS object that contains non-primitive subtypes.
  177. *
  178. * Properties of the value that aren't included in the specializations
  179. * will be serialized as primitive values.
  180. *
  181. * @param object specializations
  182. * A dict of property names => type
  183. */
  184. types.addDictType = function (name, specializations) {
  185. return types.addType(name, {
  186. category: "dict",
  187. specializations: specializations,
  188. read: (v, ctx) => {
  189. let ret = {};
  190. for (let prop in v) {
  191. if (prop in specializations) {
  192. ret[prop] = types.getType(specializations[prop]).read(v[prop], ctx);
  193. } else {
  194. ret[prop] = v[prop];
  195. }
  196. }
  197. return ret;
  198. },
  199. write: (v, ctx) => {
  200. let ret = {};
  201. for (let prop in v) {
  202. if (prop in specializations) {
  203. ret[prop] = types.getType(specializations[prop]).write(v[prop], ctx);
  204. } else {
  205. ret[prop] = v[prop];
  206. }
  207. }
  208. return ret;
  209. }
  210. });
  211. };
  212. /**
  213. * Register an actor type with the type system.
  214. *
  215. * Types are marshalled differently when communicating server->client
  216. * than they are when communicating client->server. The server needs
  217. * to provide useful information to the client, so uses the actor's
  218. * `form` method to get a json representation of the actor. When
  219. * making a request from the client we only need the actor ID string.
  220. *
  221. * This function can be called before the associated actor has been
  222. * constructed, but the read and write methods won't work until
  223. * the associated addActorImpl or addActorFront methods have been
  224. * called during actor/front construction.
  225. *
  226. * @param string name
  227. * The typestring to register.
  228. */
  229. types.addActorType = function (name) {
  230. let type = types.addType(name, {
  231. _actor: true,
  232. category: "actor",
  233. read: (v, ctx, detail) => {
  234. // If we're reading a request on the server side, just
  235. // find the actor registered with this actorID.
  236. if (ctx instanceof Actor) {
  237. return ctx.conn.getActor(v);
  238. }
  239. // Reading a response on the client side, check for an
  240. // existing front on the connection, and create the front
  241. // if it isn't found.
  242. let actorID = typeof (v) === "string" ? v : v.actor;
  243. let front = ctx.conn.getActor(actorID);
  244. if (!front) {
  245. front = new type.frontClass(ctx.conn);
  246. front.actorID = actorID;
  247. ctx.marshallPool().manage(front);
  248. }
  249. v = type.formType(detail).read(v, front, detail);
  250. front.form(v, detail, ctx);
  251. return front;
  252. },
  253. write: (v, ctx, detail) => {
  254. // If returning a response from the server side, make sure
  255. // the actor is added to a parent object and return its form.
  256. if (v instanceof Actor) {
  257. if (!v.actorID) {
  258. ctx.marshallPool().manage(v);
  259. }
  260. return type.formType(detail).write(v.form(detail), ctx, detail);
  261. }
  262. // Writing a request from the client side, just send the actor id.
  263. return v.actorID;
  264. },
  265. formType: (detail) => {
  266. if (!("formType" in type.actorSpec)) {
  267. return types.Primitive;
  268. }
  269. let formAttr = "formType";
  270. if (detail) {
  271. formAttr += "#" + detail;
  272. }
  273. if (!(formAttr in type.actorSpec)) {
  274. throw new Error("No type defined for " + formAttr);
  275. }
  276. return type.actorSpec[formAttr];
  277. }
  278. });
  279. return type;
  280. };
  281. types.addNullableType = function (subtype) {
  282. subtype = types.getType(subtype);
  283. return types.addType("nullable:" + subtype.name, {
  284. category: "nullable",
  285. read: (value, ctx) => {
  286. if (value == null) {
  287. return value;
  288. }
  289. return subtype.read(value, ctx);
  290. },
  291. write: (value, ctx) => {
  292. if (value == null) {
  293. return value;
  294. }
  295. return subtype.write(value, ctx);
  296. }
  297. });
  298. };
  299. /**
  300. * Register an actor detail type. This is just like an actor type, but
  301. * will pass a detail hint to the actor's form method during serialization/
  302. * deserialization.
  303. *
  304. * This is called by getType() when passed an 'actorType#detail' string.
  305. *
  306. * @param string name
  307. * The typestring to register this type as.
  308. * @param type actorType
  309. * The actor type you'll be detailing.
  310. * @param string detail
  311. * The detail to pass.
  312. */
  313. types.addActorDetail = function (name, actorType, detail) {
  314. actorType = types.getType(actorType);
  315. if (!actorType._actor) {
  316. throw Error("Details only apply to actor types, tried to add detail '" + detail + "'' to " + actorType.name + "\n");
  317. }
  318. return types.addType(name, {
  319. _actor: true,
  320. category: "detail",
  321. read: (v, ctx) => actorType.read(v, ctx, detail),
  322. write: (v, ctx) => actorType.write(v, ctx, detail)
  323. });
  324. };
  325. /**
  326. * Register an actor lifetime. This lets the type system find a parent
  327. * actor that differs from the actor fulfilling the request.
  328. *
  329. * @param string name
  330. * The lifetime name to use in typestrings.
  331. * @param string prop
  332. * The property of the actor that holds the parent that should be used.
  333. */
  334. types.addLifetime = function (name, prop) {
  335. if (registeredLifetimes.has(name)) {
  336. throw Error("Lifetime '" + name + "' already registered.");
  337. }
  338. registeredLifetimes.set(name, prop);
  339. };
  340. /**
  341. * Remove a previously-registered lifetime. Useful for lifetimes registered
  342. * in addons.
  343. */
  344. types.removeLifetime = function (name) {
  345. registeredLifetimes.delete(name);
  346. };
  347. /**
  348. * Register a lifetime type. This creates an actor type tied to the given
  349. * lifetime.
  350. *
  351. * This is called by getType() when passed a '<lifetimeType>:<actorType>'
  352. * typestring.
  353. *
  354. * @param string lifetime
  355. * A lifetime string previously regisered with addLifetime()
  356. * @param type subtype
  357. * An actor type
  358. */
  359. types.addLifetimeType = function (lifetime, subtype) {
  360. subtype = types.getType(subtype);
  361. if (!subtype._actor) {
  362. throw Error("Lifetimes only apply to actor types, tried to apply lifetime '" + lifetime + "'' to " + subtype.name);
  363. }
  364. let prop = registeredLifetimes.get(lifetime);
  365. return types.addType(lifetime + ":" + subtype.name, {
  366. category: "lifetime",
  367. read: (value, ctx) => subtype.read(value, ctx[prop]),
  368. write: (value, ctx) => subtype.write(value, ctx[prop])
  369. });
  370. };
  371. // Add a few named primitive types.
  372. types.Primitive = types.addType("primitive");
  373. types.String = types.addType("string");
  374. types.Number = types.addType("number");
  375. types.Boolean = types.addType("boolean");
  376. types.JSON = types.addType("json");
  377. /**
  378. * Request/Response templates and generation
  379. *
  380. * Request packets are specified as json templates with
  381. * Arg and Option placeholders where arguments should be
  382. * placed.
  383. *
  384. * Reponse packets are also specified as json templates,
  385. * with a RetVal placeholder where the return value should be
  386. * placed.
  387. */
  388. /**
  389. * Placeholder for simple arguments.
  390. *
  391. * @param number index
  392. * The argument index to place at this position.
  393. * @param type type
  394. * The argument should be marshalled as this type.
  395. * @constructor
  396. */
  397. var Arg = Class({
  398. initialize: function (index, type) {
  399. this.index = index;
  400. this.type = types.getType(type);
  401. },
  402. write: function (arg, ctx) {
  403. return this.type.write(arg, ctx);
  404. },
  405. read: function (v, ctx, outArgs) {
  406. outArgs[this.index] = this.type.read(v, ctx);
  407. },
  408. describe: function () {
  409. return {
  410. _arg: this.index,
  411. type: this.type.name,
  412. };
  413. }
  414. });
  415. exports.Arg = Arg;
  416. /**
  417. * Placeholder for an options argument value that should be hoisted
  418. * into the packet.
  419. *
  420. * If provided in a method specification:
  421. *
  422. * { optionArg: Option(1)}
  423. *
  424. * Then arguments[1].optionArg will be placed in the packet in this
  425. * value's place.
  426. *
  427. * @param number index
  428. * The argument index of the options value.
  429. * @param type type
  430. * The argument should be marshalled as this type.
  431. * @constructor
  432. */
  433. var Option = Class({
  434. extends: Arg,
  435. initialize: function (index, type) {
  436. Arg.prototype.initialize.call(this, index, type);
  437. },
  438. write: function (arg, ctx, name) {
  439. // Ignore if arg is undefined or null; allow other falsy values
  440. if (arg == undefined || arg[name] == undefined) {
  441. return undefined;
  442. }
  443. let v = arg[name];
  444. return this.type.write(v, ctx);
  445. },
  446. read: function (v, ctx, outArgs, name) {
  447. if (outArgs[this.index] === undefined) {
  448. outArgs[this.index] = {};
  449. }
  450. if (v === undefined) {
  451. return;
  452. }
  453. outArgs[this.index][name] = this.type.read(v, ctx);
  454. },
  455. describe: function () {
  456. return {
  457. _option: this.index,
  458. type: this.type.name,
  459. };
  460. }
  461. });
  462. exports.Option = Option;
  463. /**
  464. * Placeholder for return values in a response template.
  465. *
  466. * @param type type
  467. * The return value should be marshalled as this type.
  468. */
  469. var RetVal = Class({
  470. initialize: function (type) {
  471. this.type = types.getType(type);
  472. },
  473. write: function (v, ctx) {
  474. return this.type.write(v, ctx);
  475. },
  476. read: function (v, ctx) {
  477. return this.type.read(v, ctx);
  478. },
  479. describe: function () {
  480. return {
  481. _retval: this.type.name
  482. };
  483. }
  484. });
  485. exports.RetVal = RetVal;
  486. /* Template handling functions */
  487. /**
  488. * Get the value at a given path, or undefined if not found.
  489. */
  490. function getPath(obj, path) {
  491. for (let name of path) {
  492. if (!(name in obj)) {
  493. return undefined;
  494. }
  495. obj = obj[name];
  496. }
  497. return obj;
  498. }
  499. /**
  500. * Find Placeholders in the template and save them along with their
  501. * paths.
  502. */
  503. function findPlaceholders(template, constructor, path = [], placeholders = []) {
  504. if (!template || typeof (template) != "object") {
  505. return placeholders;
  506. }
  507. if (template instanceof constructor) {
  508. placeholders.push({ placeholder: template, path: [...path] });
  509. return placeholders;
  510. }
  511. for (let name in template) {
  512. path.push(name);
  513. findPlaceholders(template[name], constructor, path, placeholders);
  514. path.pop();
  515. }
  516. return placeholders;
  517. }
  518. function describeTemplate(template) {
  519. return JSON.parse(JSON.stringify(template, (key, value) => {
  520. if (value.describe) {
  521. return value.describe();
  522. }
  523. return value;
  524. }));
  525. }
  526. /**
  527. * Manages a request template.
  528. *
  529. * @param object template
  530. * The request template.
  531. * @construcor
  532. */
  533. var Request = Class({
  534. initialize: function (template = {}) {
  535. this.type = template.type;
  536. this.template = template;
  537. this.args = findPlaceholders(template, Arg);
  538. },
  539. /**
  540. * Write a request.
  541. *
  542. * @param array fnArgs
  543. * The function arguments to place in the request.
  544. * @param object ctx
  545. * The object making the request.
  546. * @returns a request packet.
  547. */
  548. write: function (fnArgs, ctx) {
  549. let str = JSON.stringify(this.template, (key, value) => {
  550. if (value instanceof Arg) {
  551. return value.write(value.index in fnArgs ? fnArgs[value.index] : undefined,
  552. ctx, key);
  553. }
  554. return value;
  555. });
  556. return JSON.parse(str);
  557. },
  558. /**
  559. * Read a request.
  560. *
  561. * @param object packet
  562. * The request packet.
  563. * @param object ctx
  564. * The object making the request.
  565. * @returns an arguments array
  566. */
  567. read: function (packet, ctx) {
  568. let fnArgs = [];
  569. for (let templateArg of this.args) {
  570. let arg = templateArg.placeholder;
  571. let path = templateArg.path;
  572. let name = path[path.length - 1];
  573. arg.read(getPath(packet, path), ctx, fnArgs, name);
  574. }
  575. return fnArgs;
  576. },
  577. describe: function () { return describeTemplate(this.template); }
  578. });
  579. /**
  580. * Manages a response template.
  581. *
  582. * @param object template
  583. * The response template.
  584. * @construcor
  585. */
  586. var Response = Class({
  587. initialize: function (template = {}) {
  588. this.template = template;
  589. let placeholders = findPlaceholders(template, RetVal);
  590. if (placeholders.length > 1) {
  591. throw Error("More than one RetVal specified in response");
  592. }
  593. let placeholder = placeholders.shift();
  594. if (placeholder) {
  595. this.retVal = placeholder.placeholder;
  596. this.path = placeholder.path;
  597. }
  598. },
  599. /**
  600. * Write a response for the given return value.
  601. *
  602. * @param val ret
  603. * The return value.
  604. * @param object ctx
  605. * The object writing the response.
  606. */
  607. write: function (ret, ctx) {
  608. return JSON.parse(JSON.stringify(this.template, function (key, value) {
  609. if (value instanceof RetVal) {
  610. return value.write(ret, ctx);
  611. }
  612. return value;
  613. }));
  614. },
  615. /**
  616. * Read a return value from the given response.
  617. *
  618. * @param object packet
  619. * The response packet.
  620. * @param object ctx
  621. * The object reading the response.
  622. */
  623. read: function (packet, ctx) {
  624. if (!this.retVal) {
  625. return undefined;
  626. }
  627. let v = getPath(packet, this.path);
  628. return this.retVal.read(v, ctx);
  629. },
  630. describe: function () { return describeTemplate(this.template); }
  631. });
  632. /**
  633. * Actor and Front implementations
  634. */
  635. /**
  636. * A protocol object that can manage the lifetime of other protocol
  637. * objects.
  638. */
  639. var Pool = Class({
  640. extends: EventTarget,
  641. /**
  642. * Pools are used on both sides of the connection to help coordinate
  643. * lifetimes.
  644. *
  645. * @param optional conn
  646. * Either a DebuggerServerConnection or a DebuggerClient. Must have
  647. * addActorPool, removeActorPool, and poolFor.
  648. * conn can be null if the subclass provides a conn property.
  649. * @constructor
  650. */
  651. initialize: function (conn) {
  652. if (conn) {
  653. this.conn = conn;
  654. }
  655. },
  656. /**
  657. * Return the parent pool for this client.
  658. */
  659. parent: function () { return this.conn.poolFor(this.actorID); },
  660. /**
  661. * Override this if you want actors returned by this actor
  662. * to belong to a different actor by default.
  663. */
  664. marshallPool: function () { return this; },
  665. /**
  666. * Pool is the base class for all actors, even leaf nodes.
  667. * If the child map is actually referenced, go ahead and create
  668. * the stuff needed by the pool.
  669. */
  670. __poolMap: null,
  671. get _poolMap() {
  672. if (this.__poolMap) return this.__poolMap;
  673. this.__poolMap = new Map();
  674. this.conn.addActorPool(this);
  675. return this.__poolMap;
  676. },
  677. /**
  678. * Add an actor as a child of this pool.
  679. */
  680. manage: function (actor) {
  681. if (!actor.actorID) {
  682. actor.actorID = this.conn.allocID(actor.actorPrefix || actor.typeName);
  683. }
  684. this._poolMap.set(actor.actorID, actor);
  685. return actor;
  686. },
  687. /**
  688. * Remove an actor as a child of this pool.
  689. */
  690. unmanage: function (actor) {
  691. this.__poolMap && this.__poolMap.delete(actor.actorID);
  692. },
  693. // true if the given actor ID exists in the pool.
  694. has: function (actorID) {
  695. return this.__poolMap && this._poolMap.has(actorID);
  696. },
  697. // The actor for a given actor id stored in this pool
  698. actor: function (actorID) {
  699. return this.__poolMap ? this._poolMap.get(actorID) : null;
  700. },
  701. // Same as actor, should update debugger connection to use 'actor'
  702. // and then remove this.
  703. get: function (actorID) {
  704. return this.__poolMap ? this._poolMap.get(actorID) : null;
  705. },
  706. // True if this pool has no children.
  707. isEmpty: function () {
  708. return !this.__poolMap || this._poolMap.size == 0;
  709. },
  710. /**
  711. * Destroy this item, removing it from a parent if it has one,
  712. * and destroying all children if necessary.
  713. */
  714. destroy: function () {
  715. let parent = this.parent();
  716. if (parent) {
  717. parent.unmanage(this);
  718. }
  719. if (!this.__poolMap) {
  720. return;
  721. }
  722. for (let actor of this.__poolMap.values()) {
  723. // Self-owned actors are ok, but don't need destroying twice.
  724. if (actor === this) {
  725. continue;
  726. }
  727. let destroy = actor.destroy;
  728. if (destroy) {
  729. // Disconnect destroy while we're destroying in case of (misbehaving)
  730. // circular ownership.
  731. actor.destroy = null;
  732. destroy.call(actor);
  733. actor.destroy = destroy;
  734. }
  735. }
  736. this.conn.removeActorPool(this, true);
  737. this.__poolMap.clear();
  738. this.__poolMap = null;
  739. },
  740. /**
  741. * For getting along with the debugger server pools, should be removable
  742. * eventually.
  743. */
  744. cleanup: function () {
  745. this.destroy();
  746. }
  747. });
  748. exports.Pool = Pool;
  749. /**
  750. * An actor in the actor tree.
  751. */
  752. var Actor = Class({
  753. extends: Pool,
  754. // Will contain the actor's ID
  755. actorID: null,
  756. /**
  757. * Initialize an actor.
  758. *
  759. * @param optional conn
  760. * Either a DebuggerServerConnection or a DebuggerClient. Must have
  761. * addActorPool, removeActorPool, and poolFor.
  762. * conn can be null if the subclass provides a conn property.
  763. * @constructor
  764. */
  765. initialize: function (conn) {
  766. Pool.prototype.initialize.call(this, conn);
  767. // Forward events to the connection.
  768. if (this._actorSpec && this._actorSpec.events) {
  769. for (let key of this._actorSpec.events.keys()) {
  770. let name = key;
  771. let sendEvent = this._sendEvent.bind(this, name);
  772. this.on(name, (...args) => {
  773. sendEvent.apply(null, args);
  774. });
  775. }
  776. }
  777. },
  778. toString: function () { return "[Actor " + this.typeName + "/" + this.actorID + "]"; },
  779. _sendEvent: function (name, ...args) {
  780. if (!this._actorSpec.events.has(name)) {
  781. // It's ok to emit events that don't go over the wire.
  782. return;
  783. }
  784. let request = this._actorSpec.events.get(name);
  785. let packet;
  786. try {
  787. packet = request.write(args, this);
  788. } catch (ex) {
  789. console.error("Error sending event: " + name);
  790. throw ex;
  791. }
  792. packet.from = packet.from || this.actorID;
  793. this.conn.send(packet);
  794. },
  795. destroy: function () {
  796. Pool.prototype.destroy.call(this);
  797. this.actorID = null;
  798. },
  799. /**
  800. * Override this method in subclasses to serialize the actor.
  801. * @param [optional] string hint
  802. * Optional string to customize the form.
  803. * @returns A jsonable object.
  804. */
  805. form: function (hint) {
  806. return { actor: this.actorID };
  807. },
  808. writeError: function (error) {
  809. console.error(error);
  810. if (error.stack) {
  811. dump(error.stack);
  812. }
  813. this.conn.send({
  814. from: this.actorID,
  815. error: error.error || "unknownError",
  816. message: error.message
  817. });
  818. },
  819. _queueResponse: function (create) {
  820. let pending = this._pendingResponse || promise.resolve(null);
  821. let response = create(pending);
  822. this._pendingResponse = response;
  823. }
  824. });
  825. exports.Actor = Actor;
  826. /**
  827. * Tags a prtotype method as an actor method implementation.
  828. *
  829. * @param function fn
  830. * The implementation function, will be returned.
  831. * @param spec
  832. * The method specification, with the following (optional) properties:
  833. * request (object): a request template.
  834. * response (object): a response template.
  835. * oneway (bool): 'true' if no response should be sent.
  836. */
  837. exports.method = function (fn, spec = {}) {
  838. fn._methodSpec = Object.freeze(spec);
  839. if (spec.request) Object.freeze(spec.request);
  840. if (spec.response) Object.freeze(spec.response);
  841. return fn;
  842. };
  843. /**
  844. * Generates an actor specification from an actor description.
  845. */
  846. var generateActorSpec = function (actorDesc) {
  847. let actorSpec = {
  848. typeName: actorDesc.typeName,
  849. methods: []
  850. };
  851. // Find method and form specifications attached to properties.
  852. for (let name of Object.getOwnPropertyNames(actorDesc)) {
  853. let desc = Object.getOwnPropertyDescriptor(actorDesc, name);
  854. if (!desc.value) {
  855. continue;
  856. }
  857. if (name.startsWith("formType")) {
  858. if (typeof (desc.value) === "string") {
  859. actorSpec[name] = types.getType(desc.value);
  860. } else if (desc.value.name && registeredTypes.has(desc.value.name)) {
  861. actorSpec[name] = desc.value;
  862. } else {
  863. // Shorthand for a newly-registered DictType.
  864. actorSpec[name] = types.addDictType(actorDesc.typeName + "__" + name, desc.value);
  865. }
  866. }
  867. if (desc.value._methodSpec) {
  868. let methodSpec = desc.value._methodSpec;
  869. let spec = {};
  870. spec.name = methodSpec.name || name;
  871. spec.request = Request(object.merge({type: spec.name}, methodSpec.request || undefined));
  872. spec.response = Response(methodSpec.response || undefined);
  873. spec.release = methodSpec.release;
  874. spec.oneway = methodSpec.oneway;
  875. actorSpec.methods.push(spec);
  876. }
  877. }
  878. // Find additional method specifications
  879. if (actorDesc.methods) {
  880. for (let name in actorDesc.methods) {
  881. let methodSpec = actorDesc.methods[name];
  882. let spec = {};
  883. spec.name = methodSpec.name || name;
  884. spec.request = Request(object.merge({type: spec.name}, methodSpec.request || undefined));
  885. spec.response = Response(methodSpec.response || undefined);
  886. spec.release = methodSpec.release;
  887. spec.oneway = methodSpec.oneway;
  888. actorSpec.methods.push(spec);
  889. }
  890. }
  891. // Find event specifications
  892. if (actorDesc.events) {
  893. actorSpec.events = new Map();
  894. for (let name in actorDesc.events) {
  895. let eventRequest = actorDesc.events[name];
  896. Object.freeze(eventRequest);
  897. actorSpec.events.set(name, Request(object.merge({type: name}, eventRequest)));
  898. }
  899. }
  900. if (!registeredTypes.has(actorSpec.typeName)) {
  901. types.addActorType(actorSpec.typeName);
  902. }
  903. registeredTypes.get(actorSpec.typeName).actorSpec = actorSpec;
  904. return actorSpec;
  905. };
  906. exports.generateActorSpec = generateActorSpec;
  907. /**
  908. * Generates request handlers as described by the given actor specification on
  909. * the given actor prototype. Returns the actor prototype.
  910. */
  911. var generateRequestHandlers = function (actorSpec, actorProto) {
  912. if (actorProto._actorSpec) {
  913. throw new Error("actorProto called twice on the same actor prototype!");
  914. }
  915. actorProto.typeName = actorSpec.typeName;
  916. // Generate request handlers for each method definition
  917. actorProto.requestTypes = Object.create(null);
  918. actorSpec.methods.forEach(spec => {
  919. let handler = function (packet, conn) {
  920. try {
  921. let args;
  922. try {
  923. args = spec.request.read(packet, this);
  924. } catch (ex) {
  925. console.error("Error reading request: " + packet.type);
  926. throw ex;
  927. }
  928. let ret = this[spec.name].apply(this, args);
  929. let sendReturn = (ret) => {
  930. if (spec.oneway) {
  931. // No need to send a response.
  932. return;
  933. }
  934. let response;
  935. try {
  936. response = spec.response.write(ret, this);
  937. } catch (ex) {
  938. console.error("Error writing response to: " + spec.name);
  939. throw ex;
  940. }
  941. response.from = this.actorID;
  942. // If spec.release has been specified, destroy the object.
  943. if (spec.release) {
  944. try {
  945. this.destroy();
  946. } catch (e) {
  947. this.writeError(e);
  948. return;
  949. }
  950. }
  951. conn.send(response);
  952. };
  953. this._queueResponse(p => {
  954. return p
  955. .then(() => ret)
  956. .then(sendReturn)
  957. .then(null, this.writeError.bind(this));
  958. });
  959. } catch (e) {
  960. this._queueResponse(p => {
  961. return p.then(() => this.writeError(e));
  962. });
  963. }
  964. };
  965. actorProto.requestTypes[spec.request.type] = handler;
  966. });
  967. actorProto._actorSpec = actorSpec;
  968. return actorProto;
  969. };
  970. /**
  971. * THIS METHOD IS DEPRECATED, AND PRESERVED ONLY FOR ADD-ONS. IT SHOULD NOT BE
  972. * USED INSIDE THE TREE.
  973. *
  974. * Create an actor class for the given actor prototype.
  975. *
  976. * @param object actorProto
  977. * The actor prototype. Must have a 'typeName' property,
  978. * should have method definitions, can have event definitions.
  979. */
  980. exports.ActorClass = function (actorProto) {
  981. return ActorClassWithSpec(generateActorSpec(actorProto), actorProto);
  982. };
  983. /**
  984. * THIS METHOD IS DEPRECATED, AND PRESERVED ONLY FOR ADD-ONS. IT SHOULD NOT BE
  985. * USED INSIDE THE TREE.
  986. *
  987. * Create an actor class for the given actor specification and prototype.
  988. *
  989. * @param object actorSpec
  990. * The actor specification. Must have a 'typeName' property.
  991. * @param object actorProto
  992. * The actor prototype. Should have method definitions, can have event
  993. * definitions.
  994. */
  995. var ActorClassWithSpec = function (actorSpec, actorProto) {
  996. if (!actorSpec.typeName) {
  997. throw Error("Actor specification must have a typeName member.");
  998. }
  999. actorProto.extends = Actor;
  1000. let cls = Class(generateRequestHandlers(actorSpec, actorProto));
  1001. return cls;
  1002. };
  1003. exports.ActorClassWithSpec = ActorClassWithSpec;
  1004. /**
  1005. * Base class for client-side actor fronts.
  1006. */
  1007. var Front = Class({
  1008. extends: Pool,
  1009. actorID: null,
  1010. /**
  1011. * The base class for client-side actor fronts.
  1012. *
  1013. * @param optional conn
  1014. * Either a DebuggerServerConnection or a DebuggerClient. Must have
  1015. * addActorPool, removeActorPool, and poolFor.
  1016. * conn can be null if the subclass provides a conn property.
  1017. * @param optional form
  1018. * The json form provided by the server.
  1019. * @constructor
  1020. */
  1021. initialize: function (conn = null, form = null, detail = null, context = null) {
  1022. Pool.prototype.initialize.call(this, conn);
  1023. this._requests = [];
  1024. // protocol.js no longer uses this data in the constructor, only external
  1025. // uses do. External usage of manually-constructed fronts will be
  1026. // drastically reduced if we convert the root and tab actors to
  1027. // protocol.js, in which case this can probably go away.
  1028. if (form) {
  1029. this.actorID = form.actor;
  1030. form = types.getType(this.typeName).formType(detail).read(form, this, detail);
  1031. this.form(form, detail, context);
  1032. }
  1033. },
  1034. destroy: function () {
  1035. // Reject all outstanding requests, they won't make sense after
  1036. // the front is destroyed.
  1037. while (this._requests && this._requests.length > 0) {
  1038. let { deferred, to, type, stack } = this._requests.shift();
  1039. let msg = "Connection closed, pending request to " + to +
  1040. ", type " + type + " failed" +
  1041. "\n\nRequest stack:\n" + stack.formattedStack;
  1042. deferred.reject(new Error(msg));
  1043. }
  1044. Pool.prototype.destroy.call(this);
  1045. this.actorID = null;
  1046. },
  1047. manage: function (front) {
  1048. if (!front.actorID) {
  1049. throw new Error("Can't manage front without an actor ID.\n" +
  1050. "Ensure server supports " + front.typeName + ".");
  1051. }
  1052. return Pool.prototype.manage.call(this, front);
  1053. },
  1054. /**
  1055. * @returns a promise that will resolve to the actorID this front
  1056. * represents.
  1057. */
  1058. actor: function () { return promise.resolve(this.actorID); },
  1059. toString: function () { return "[Front for " + this.typeName + "/" + this.actorID + "]"; },
  1060. /**
  1061. * Update the actor from its representation.
  1062. * Subclasses should override this.
  1063. */
  1064. form: function (form) {},
  1065. /**
  1066. * Send a packet on the connection.
  1067. */
  1068. send: function (packet) {
  1069. if (packet.to) {
  1070. this.conn._transport.send(packet);
  1071. } else {
  1072. this.actor().then(actorID => {
  1073. packet.to = actorID;
  1074. this.conn._transport.send(packet);
  1075. }).then(null, e => console.error(e));
  1076. }
  1077. },
  1078. /**
  1079. * Send a two-way request on the connection.
  1080. */
  1081. request: function (packet) {
  1082. let deferred = defer();
  1083. // Save packet basics for debugging
  1084. let { to, type } = packet;
  1085. this._requests.push({
  1086. deferred,
  1087. to: to || this.actorID,
  1088. type,
  1089. stack: getStack(),
  1090. });
  1091. this.send(packet);
  1092. return deferred.promise;
  1093. },
  1094. /**
  1095. * Handler for incoming packets from the client's actor.
  1096. */
  1097. onPacket: function (packet) {
  1098. // Pick off event packets
  1099. let type = packet.type || undefined;
  1100. if (this._clientSpec.events && this._clientSpec.events.has(type)) {
  1101. let event = this._clientSpec.events.get(packet.type);
  1102. let args;
  1103. try {
  1104. args = event.request.read(packet, this);
  1105. } catch (ex) {
  1106. console.error("Error reading event: " + packet.type);
  1107. console.exception(ex);
  1108. throw ex;
  1109. }
  1110. if (event.pre) {
  1111. let results = event.pre.map(pre => pre.apply(this, args));
  1112. // Check to see if any of the preEvents returned a promise -- if so,
  1113. // wait for their resolution before emitting. Otherwise, emit synchronously.
  1114. if (results.some(result => result && typeof result.then === "function")) {
  1115. promise.all(results).then(() => events.emit.apply(null, [this, event.name].concat(args)));
  1116. return;
  1117. }
  1118. }
  1119. events.emit.apply(null, [this, event.name].concat(args));
  1120. return;
  1121. }
  1122. // Remaining packets must be responses.
  1123. if (this._requests.length === 0) {
  1124. let msg = "Unexpected packet " + this.actorID + ", " + JSON.stringify(packet);
  1125. let err = Error(msg);
  1126. console.error(err);
  1127. throw err;
  1128. }
  1129. let { deferred, stack } = this._requests.shift();
  1130. callFunctionWithAsyncStack(() => {
  1131. if (packet.error) {
  1132. // "Protocol error" is here to avoid TBPL heuristics. See also
  1133. // https://dxr.mozilla.org/webtools-central/source/tbpl/php/inc/GeneralErrorFilter.php
  1134. let message;
  1135. if (packet.error && packet.message) {
  1136. message = "Protocol error (" + packet.error + "): " + packet.message;
  1137. } else {
  1138. message = packet.error;
  1139. }
  1140. deferred.reject(message);
  1141. } else {
  1142. deferred.resolve(packet);
  1143. }
  1144. }, stack, "DevTools RDP");
  1145. }
  1146. });
  1147. exports.Front = Front;
  1148. /**
  1149. * A method tagged with preEvent will be called after recieving a packet
  1150. * for that event, and before the front emits the event.
  1151. */
  1152. exports.preEvent = function (eventName, fn) {
  1153. fn._preEvent = eventName;
  1154. return fn;
  1155. };
  1156. /**
  1157. * Mark a method as a custom front implementation, replacing the generated
  1158. * front method.
  1159. *
  1160. * @param function fn
  1161. * The front implementation, will be returned.
  1162. * @param object options
  1163. * Options object:
  1164. * impl (string): If provided, the generated front method will be
  1165. * stored as this property on the prototype.
  1166. */
  1167. exports.custom = function (fn, options = {}) {
  1168. fn._customFront = options;
  1169. return fn;
  1170. };
  1171. function prototypeOf(obj) {
  1172. return typeof (obj) === "function" ? obj.prototype : obj;
  1173. }
  1174. /**
  1175. * Generates request methods as described by the given actor specification on
  1176. * the given front prototype. Returns the front prototype.
  1177. */
  1178. var generateRequestMethods = function (actorSpec, frontProto) {
  1179. if (frontProto._actorSpec) {
  1180. throw new Error("frontProto called twice on the same front prototype!");
  1181. }
  1182. frontProto.typeName = actorSpec.typeName;
  1183. // Generate request methods.
  1184. let methods = actorSpec.methods;
  1185. methods.forEach(spec => {
  1186. let name = spec.name;
  1187. // If there's already a property by this name in the front, it must
  1188. // be a custom front method.
  1189. if (name in frontProto) {
  1190. let custom = frontProto[spec.name]._customFront;
  1191. if (custom === undefined) {
  1192. throw Error("Existing method for " + spec.name + " not marked customFront while processing " + actorType.typeName + ".");
  1193. }
  1194. // If the user doesn't need the impl don't generate it.
  1195. if (!custom.impl) {
  1196. return;
  1197. }
  1198. name = custom.impl;
  1199. }
  1200. frontProto[name] = function (...args) {
  1201. let packet;
  1202. try {
  1203. packet = spec.request.write(args, this);
  1204. } catch (ex) {
  1205. console.error("Error writing request: " + name);
  1206. throw ex;
  1207. }
  1208. if (spec.oneway) {
  1209. // Fire-and-forget oneway packets.
  1210. this.send(packet);
  1211. return undefined;
  1212. }
  1213. return this.request(packet).then(response => {
  1214. let ret;
  1215. try {
  1216. ret = spec.response.read(response, this);
  1217. } catch (ex) {
  1218. console.error("Error reading response to: " + name);
  1219. throw ex;
  1220. }
  1221. return ret;
  1222. });
  1223. };
  1224. // Release methods should call the destroy function on return.
  1225. if (spec.release) {
  1226. let fn = frontProto[name];
  1227. frontProto[name] = function (...args) {
  1228. return fn.apply(this, args).then(result => {
  1229. this.destroy();
  1230. return result;
  1231. });
  1232. };
  1233. }
  1234. });
  1235. // Process event specifications
  1236. frontProto._clientSpec = {};
  1237. let events = actorSpec.events;
  1238. if (events) {
  1239. // This actor has events, scan the prototype for preEvent handlers...
  1240. let preHandlers = new Map();
  1241. for (let name of Object.getOwnPropertyNames(frontProto)) {
  1242. let desc = Object.getOwnPropertyDescriptor(frontProto, name);
  1243. if (!desc.value) {
  1244. continue;
  1245. }
  1246. if (desc.value._preEvent) {
  1247. let preEvent = desc.value._preEvent;
  1248. if (!events.has(preEvent)) {
  1249. throw Error("preEvent for event that doesn't exist: " + preEvent);
  1250. }
  1251. let handlers = preHandlers.get(preEvent);
  1252. if (!handlers) {
  1253. handlers = [];
  1254. preHandlers.set(preEvent, handlers);
  1255. }
  1256. handlers.push(desc.value);
  1257. }
  1258. }
  1259. frontProto._clientSpec.events = new Map();
  1260. for (let [name, request] of events) {
  1261. frontProto._clientSpec.events.set(request.type, {
  1262. name: name,
  1263. request: request,
  1264. pre: preHandlers.get(name)
  1265. });
  1266. }
  1267. }
  1268. frontProto._actorSpec = actorSpec;
  1269. return frontProto;
  1270. };
  1271. /**
  1272. * Create a front class for the given actor class and front prototype.
  1273. *
  1274. * @param ActorClass actorType
  1275. * The actor class you're creating a front for.
  1276. * @param object frontProto
  1277. * The front prototype. Must have a 'typeName' property,
  1278. * should have method definitions, can have event definitions.
  1279. */
  1280. exports.FrontClass = function (actorType, frontProto) {
  1281. return FrontClassWithSpec(prototypeOf(actorType)._actorSpec, frontProto);
  1282. };
  1283. /**
  1284. * Create a front class for the given actor specification and front prototype.
  1285. *
  1286. * @param object actorSpec
  1287. * The actor specification you're creating a front for.
  1288. * @param object proto
  1289. * The object prototype. Must have a 'typeName' property,
  1290. * should have method definitions, can have event definitions.
  1291. */
  1292. var FrontClassWithSpec = function (actorSpec, frontProto) {
  1293. frontProto.extends = Front;
  1294. let cls = Class(generateRequestMethods(actorSpec, frontProto));
  1295. if (!registeredTypes.has(actorSpec.typeName)) {
  1296. types.addActorType(actorSpec.typeName);
  1297. }
  1298. registeredTypes.get(actorSpec.typeName).frontClass = cls;
  1299. return cls;
  1300. };
  1301. exports.FrontClassWithSpec = FrontClassWithSpec;
  1302. exports.dumpActorSpec = function (type) {
  1303. let actorSpec = type.actorSpec;
  1304. let ret = {
  1305. category: "actor",
  1306. typeName: type.name,
  1307. methods: [],
  1308. events: {}
  1309. };
  1310. for (let method of actorSpec.methods) {
  1311. ret.methods.push({
  1312. name: method.name,
  1313. release: method.release || undefined,
  1314. oneway: method.oneway || undefined,
  1315. request: method.request.describe(),
  1316. response: method.response.describe()
  1317. });
  1318. }
  1319. if (actorSpec.events) {
  1320. for (let [name, request] of actorSpec.events) {
  1321. ret.events[name] = request.describe();
  1322. }
  1323. }
  1324. JSON.stringify(ret);
  1325. return ret;
  1326. };
  1327. exports.dumpProtocolSpec = function () {
  1328. let ret = {
  1329. types: {},
  1330. };
  1331. for (let [name, type] of registeredTypes) {
  1332. // Force lazy instantiation if needed.
  1333. type = types.getType(name);
  1334. let category = type.category || undefined;
  1335. if (category === "dict") {
  1336. ret.types[name] = {
  1337. category: "dict",
  1338. typeName: name,
  1339. specializations: type.specializations
  1340. };
  1341. } else if (category === "actor") {
  1342. ret.types[name] = exports.dumpActorSpec(type);
  1343. }
  1344. }
  1345. return ret;
  1346. };