promise-hooks.js 7.16 KB
Newer Older
1 2 3
// Copyright 2020 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
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
// Flags: --allow-natives-syntax --opt --no-always-opt --no-stress-opt --deopt-every-n-times=0 --ignore-unhandled-promises

let log = [];
let asyncId = 0;

function logEvent (type, args) {
  const promise = args[0];
  promise.asyncId = promise.asyncId || ++asyncId;
  log.push({
    type,
    promise,
    parent: args[1],
    argsLength: args.length
  })
}
function initHook(...args) {
  logEvent('init', args);
}
function resolveHook(...args) {
  logEvent('resolve', args);
}
function beforeHook(...args) {
  logEvent('before', args);
}
function afterHook(...args) {
  logEvent('after', args);
}

function printLog(message) {
  console.log(` --- ${message} --- `)
  for (const event of log) {
    console.log(JSON.stringify(event))
  }
}

function assertNextEvent(type, args) {
  const [ promiseOrId, parentOrId ] = args;
  const nextEvent = log.shift();

  assertEquals(type, nextEvent.type);
  assertEquals(type === 'init' ? 2 : 1, nextEvent.argsLength);

  assertTrue(nextEvent.promise instanceof Promise);
  if (promiseOrId instanceof Promise) {
    assertEquals(promiseOrId, nextEvent.promise);
  } else {
    assertTrue(typeof promiseOrId === 'number');
    assertEquals(promiseOrId, nextEvent.promise?.asyncId);
  }

  if (parentOrId instanceof Promise) {
    assertEquals(parentOrId, nextEvent.parent);
    assertTrue(nextEvent.parent instanceof Promise);
  } else if (typeof parentOrId === 'number') {
    assertEquals(parentOrId, nextEvent.parent?.asyncId);
    assertTrue(nextEvent.parent instanceof Promise);
  } else {
    assertEquals(undefined, parentOrId);
    assertEquals(undefined, nextEvent.parent);
  }
}
function assertEmptyLog() {
  assertEquals(0, log.length);
  asyncId = 0;
  log = [];
}

// Verify basic log structure of different promise behaviours
function basicTest() {
  d8.promise.setHooks(initHook, beforeHook, afterHook, resolveHook);

  // `new Promise(...)` triggers init event with correct promise
  var done, p1 = new Promise(r => done = r);
  %PerformMicrotaskCheckpoint();
  assertNextEvent('init', [ p1 ]);
  assertEmptyLog();

  // `promise.then(...)` triggers init event with correct promise and parent
  var p2 = p1.then(() => { });
  %PerformMicrotaskCheckpoint();
  assertNextEvent('init', [ p2, p1 ]);
  assertEmptyLog();

  // `resolve(...)` triggers resolve event and any already attached continuations
  done();
  %PerformMicrotaskCheckpoint();
  assertNextEvent('resolve', [ p1 ]);
  assertNextEvent('before', [ p2 ]);
  assertNextEvent('resolve', [ p2 ]);
  assertNextEvent('after', [ p2 ]);
  assertEmptyLog();

  // `reject(...)` triggers the resolve event
  var done, p3 = new Promise((_, r) => done = r);
  done();
  %PerformMicrotaskCheckpoint();
  assertNextEvent('init', [ p3 ]);
  assertNextEvent('resolve', [ p3 ]);
  assertEmptyLog();

  // `promise.catch(...)` triggers init event with correct promise and parent
  // When the promise is already completed, the continuation should also run
  // immediately at the next checkpoint.
  var p4 = p3.catch(() => { });
  %PerformMicrotaskCheckpoint();
  assertNextEvent('init', [ p4, p3 ]);
  assertNextEvent('before', [ p4 ]);
  assertNextEvent('resolve', [ p4 ]);
  assertNextEvent('after', [ p4 ]);
  assertEmptyLog();

  // Detach hooks
  d8.promise.setHooks();
}

// Exceptions thrown in hook handlers should not raise or reject
function exceptions() {
  function thrower() {
    throw new Error('unexpected!');
  }

  // Init hook
  d8.promise.setHooks(thrower);
  assertDoesNotThrow(() => {
    Promise.resolve()
      .catch(assertUnreachable);
  });
  %PerformMicrotaskCheckpoint();
  d8.promise.setHooks();

  // Before hook
  d8.promise.setHooks(undefined, thrower);
  assertDoesNotThrow(() => {
    Promise.resolve()
      .then(() => {})
      .catch(assertUnreachable);
  });
  %PerformMicrotaskCheckpoint();
  d8.promise.setHooks();

  // After hook
  d8.promise.setHooks(undefined, undefined, thrower);
  assertDoesNotThrow(() => {
    Promise.resolve()
      .then(() => {})
      .catch(assertUnreachable);
  });
  %PerformMicrotaskCheckpoint();
  d8.promise.setHooks();

  // Resolve hook
  d8.promise.setHooks(undefined, undefined, undefined, thrower);
  assertDoesNotThrow(() => {
    Promise.resolve()
      .catch(assertUnreachable);
  });
  %PerformMicrotaskCheckpoint();
  d8.promise.setHooks();

  // Resolve hook for a reject
  d8.promise.setHooks(undefined, undefined, undefined, thrower);
  assertDoesNotThrow(() => {
    Promise.reject()
      .then(assertUnreachable)
      .catch();
  });
  %PerformMicrotaskCheckpoint();
  d8.promise.setHooks();
}

// For now, expect the optimizer to bail out on async functions
// when context promise hooks are attached.
function optimizerBailout(test, verify) {
  // Warm up test method
  %PrepareFunctionForOptimization(test);
  assertUnoptimized(test);
  test();
  test();
  test();
  %PerformMicrotaskCheckpoint();

  // Prove transition to optimized code when no hooks are present
  assertUnoptimized(test);
  %OptimizeFunctionOnNextCall(test);
  test();
  assertOptimized(test);
  %PerformMicrotaskCheckpoint();

  // Verify that attaching hooks deopts the async function
  d8.promise.setHooks(initHook, beforeHook, afterHook, resolveHook);
  // assertUnoptimized(test);

  // Verify log structure of deoptimized call
  %PrepareFunctionForOptimization(test);
  test();
  %PerformMicrotaskCheckpoint();

  verify();

  // Optimize and verify log structure again
  %OptimizeFunctionOnNextCall(test);
  test();
  assertOptimized(test);
  %PerformMicrotaskCheckpoint();

  verify();

  d8.promise.setHooks();
}

optimizerBailout(async () => {
  await Promise.resolve();
}, () => {
  assertNextEvent('init', [ 1 ]);
  assertNextEvent('init', [ 2 ]);
  assertNextEvent('resolve', [ 2 ]);
  assertNextEvent('init', [ 3, 2 ]);
  assertNextEvent('before', [ 3 ]);
  assertNextEvent('resolve', [ 1 ]);
  assertNextEvent('resolve', [ 3 ]);
  assertNextEvent('after', [ 3 ]);
  assertEmptyLog();
});
optimizerBailout(async () => {
  await { then (cb) { cb() } };
}, () => {
  assertNextEvent('init', [ 1 ]);
  assertNextEvent('init', [ 2, 1 ]);
  assertNextEvent('init', [ 3, 2 ]);
  assertNextEvent('before', [ 2 ]);
  assertNextEvent('resolve', [ 2 ]);
  assertNextEvent('after', [ 2 ]);
  assertNextEvent('before', [ 3 ]);
  assertNextEvent('resolve', [ 1 ]);
  assertNextEvent('resolve', [ 3 ]);
  assertNextEvent('after', [ 3 ]);
  assertEmptyLog();
});
basicTest();
exceptions();
245 246 247 248

(function regress1126309() {
  function __f_16(test) {
    test();
249
    d8.promise.setHooks(undefined, () => {});
250 251 252 253 254
    %PerformMicrotaskCheckpoint();
    d8.promise.setHooks();
  }
  __f_16(async () => { await Promise.resolve()});
})();
255 256 257 258 259 260 261 262 263 264

(function boundFunction() {
  function hook() {};
  const bound = hook.bind(this);
  d8.promise.setHooks(bound, bound, bound, bound);
  Promise.resolve();
  Promise.reject();
  %PerformMicrotaskCheckpoint();
  d8.promise.setHooks();
})();
265 266 267 268 269 270 271 272 273 274 275


(function promiseAll() {
  let initCount = 0;
  d8.promise.setHooks(() => { initCount++});
  Promise.all([Promise.resolve(1)]);
  %PerformMicrotaskCheckpoint();
  assertEquals(initCount, 3);

  d8.promise.setHooks();
})();