cm6-performance.ts 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. import { Transaction } from '@codemirror/state'
  2. import { EditorView } from '@codemirror/view'
  3. import { round } from 'lodash'
  4. import grammarlyExtensionPresent from '../shared/utils/grammarly'
  5. import getMeta from '../utils/meta'
  6. import { debugConsole } from '@/utils/debugging'
  7. const TIMER_START_NAME = 'CM6-BeforeUpdate'
  8. const TIMER_END_NAME = 'CM6-AfterUpdate'
  9. const TIMER_DOM_UPDATE_NAME = 'CM6-DomUpdate'
  10. const TIMER_MEASURE_NAME = 'CM6-Update'
  11. const TIMER_KEYPRESS_MEASURE_NAME = 'CM6-Keypress-Measure'
  12. let latestDocLength = 0
  13. const sessionStart = Date.now()
  14. let performanceOptionsSupport = false
  15. // Check that performance.mark and performance.measure accept an options object
  16. try {
  17. const testMarkName = 'featureTestMark'
  18. performance.mark(testMarkName, {
  19. startTime: performance.now(),
  20. detail: { test: 1 },
  21. })
  22. performance.clearMarks(testMarkName)
  23. const testMeasureName = 'featureTestMeasure'
  24. performance.measure(testMeasureName, {
  25. start: performance.now(),
  26. detail: { test: 1 },
  27. })
  28. performance.clearMeasures(testMeasureName)
  29. performanceOptionsSupport = true
  30. } catch (e) {}
  31. let performanceMemorySupport = false
  32. function measureMemoryUsage() {
  33. // @ts-ignore
  34. return performance.memory.usedJSHeapSize
  35. }
  36. try {
  37. if ('memory' in window.performance) {
  38. measureMemoryUsage()
  39. performanceMemorySupport = true
  40. }
  41. } catch (e) {}
  42. let performanceLongtaskSupported = false
  43. let longTaskSinceLastReportCount = 0
  44. // Detect support for long task monitoring
  45. try {
  46. if (PerformanceObserver.supportedEntryTypes.includes('longtask')) {
  47. performanceLongtaskSupported = true
  48. // Register observer for long task notifications
  49. const observer = new PerformanceObserver(list => {
  50. longTaskSinceLastReportCount += list.getEntries().length
  51. })
  52. observer.observe({ entryTypes: ['longtask'] })
  53. }
  54. } catch (e) {}
  55. function isInputOrDelete(userEventType: string | undefined) {
  56. return (
  57. !!userEventType && ['input', 'delete'].includes(userEventType.split('.')[0])
  58. )
  59. }
  60. // "keypress" is not strictly accurate; what we really mean is a user-initiated
  61. // event that either inserts or deletes exactly one character. This corresponds
  62. // to CM6 user event types input.type, delete.forward or delete.backward
  63. function isKeypress(userEventType: string | undefined) {
  64. return (
  65. !!userEventType &&
  66. ['input.type', 'delete.forward', 'delete.backward'].includes(userEventType)
  67. )
  68. }
  69. export function dispatchTimer(): {
  70. start: (trs: readonly Transaction[]) => void
  71. end: (trs: readonly Transaction[], view: EditorView) => void
  72. } {
  73. if (!performanceOptionsSupport) {
  74. return { start: () => {}, end: () => {} }
  75. }
  76. let userEventsSinceDomUpdateCount = 0
  77. let keypressesSinceDomUpdateCount = 0
  78. const unpaintedKeypressStartTimes: number[] = []
  79. const start = (trs: readonly Transaction[]) => {
  80. const keypressStart = performance.now()
  81. trs.forEach(tr => {
  82. const userEventType = tr.annotation(Transaction.userEvent)
  83. if (isKeypress(userEventType)) {
  84. unpaintedKeypressStartTimes.push(keypressStart)
  85. }
  86. })
  87. performance.mark(TIMER_START_NAME)
  88. }
  89. const end = (trs: readonly Transaction[], view: EditorView) => {
  90. performance.mark(TIMER_END_NAME)
  91. let anyInputOrDelete = false
  92. trs.forEach(tr => {
  93. const userEventType = tr.annotation(Transaction.userEvent)
  94. if (isInputOrDelete(userEventType)) {
  95. anyInputOrDelete = true
  96. ++userEventsSinceDomUpdateCount
  97. if (isKeypress(userEventType)) {
  98. ++keypressesSinceDomUpdateCount
  99. }
  100. performance.measure(TIMER_MEASURE_NAME, {
  101. start: TIMER_START_NAME,
  102. end: TIMER_END_NAME,
  103. detail: { userEventType, userEventsSinceDomUpdateCount },
  104. })
  105. }
  106. })
  107. if (anyInputOrDelete) {
  108. // The `key` property ensures that the measurement task is only run once
  109. // per measure phase
  110. view.requestMeasure({
  111. key: 'inputEventCounter',
  112. read() {
  113. performance.mark(TIMER_DOM_UPDATE_NAME, {
  114. detail: { keypressesSinceDomUpdateCount },
  115. })
  116. userEventsSinceDomUpdateCount = 0
  117. keypressesSinceDomUpdateCount = 0
  118. const keypressEnd = performance.now()
  119. for (const keypressStart of unpaintedKeypressStartTimes) {
  120. performance.measure(TIMER_KEYPRESS_MEASURE_NAME, {
  121. start: keypressStart,
  122. end: keypressEnd,
  123. })
  124. }
  125. unpaintedKeypressStartTimes.length = 0
  126. },
  127. })
  128. }
  129. latestDocLength = trs[trs.length - 1].state.doc.length
  130. }
  131. return { start, end }
  132. }
  133. function calculateMean(durations: number[]) {
  134. if (durations.length === 0) return 0
  135. const sum = durations.reduce((acc, entry) => acc + entry, 0)
  136. return sum / durations.length
  137. }
  138. function calculateMedian(sortedDurations: number[]) {
  139. if (sortedDurations.length === 0) return 0
  140. const middle = Math.floor(sortedDurations.length / 2)
  141. if (sortedDurations.length % 2 === 0) {
  142. return (sortedDurations[middle - 1] + sortedDurations[middle]) / 2
  143. }
  144. return sortedDurations[middle]
  145. }
  146. function calculate95thPercentile(sortedDurations: number[]) {
  147. if (sortedDurations.length === 0) return 0
  148. const index = Math.round((sortedDurations.length - 1) * 0.95)
  149. return sortedDurations[index]
  150. }
  151. function calculateMax(numbers: number[]) {
  152. return numbers.reduce((a, b) => Math.max(a, b), 0)
  153. }
  154. function clearCM6Perf(type: string) {
  155. switch (type) {
  156. case 'measure':
  157. performance.clearMeasures(TIMER_MEASURE_NAME)
  158. performance.clearMarks(TIMER_START_NAME)
  159. performance.clearMarks(TIMER_END_NAME)
  160. break
  161. case 'dom':
  162. performance.clearMarks(TIMER_DOM_UPDATE_NAME)
  163. break
  164. case 'keypress':
  165. performance.clearMeasures(TIMER_KEYPRESS_MEASURE_NAME)
  166. break
  167. }
  168. }
  169. // clear performance measures and marks when switching between Source and Rich Text
  170. window.addEventListener('editor:visual-switch', () => {
  171. clearCM6Perf('measure')
  172. clearCM6Perf('dom')
  173. clearCM6Perf('keypress')
  174. })
  175. export function reportCM6Perf() {
  176. // Get entries triggered by keystrokes
  177. const cm6Entries = performance.getEntriesByName(
  178. TIMER_MEASURE_NAME,
  179. 'measure'
  180. ) as PerformanceMeasure[]
  181. clearCM6Perf('measure')
  182. const inputEvents = cm6Entries.filter(({ detail }) =>
  183. isInputOrDelete(detail.userEventType)
  184. )
  185. const inputDurations = inputEvents
  186. .map(({ duration }) => duration)
  187. .sort((a, b) => a - b)
  188. const max = round(calculateMax(inputDurations), 2)
  189. const mean = round(calculateMean(inputDurations), 2)
  190. const median = round(calculateMedian(inputDurations), 2)
  191. const ninetyFifthPercentile = round(
  192. calculate95thPercentile(inputDurations),
  193. 2
  194. )
  195. const maxUserEventsBetweenDomUpdates = calculateMax(
  196. inputEvents.map(e => e.detail.userEventsSinceDomUpdateCount)
  197. )
  198. const grammarly = grammarlyExtensionPresent()
  199. const sessionLength = Math.floor((Date.now() - sessionStart) / 1000) // In seconds
  200. const memory = performanceMemorySupport ? measureMemoryUsage() : null
  201. // Get entries for keypress counts between DOM updates
  202. const domUpdateEntries = performance.getEntriesByName(
  203. TIMER_DOM_UPDATE_NAME,
  204. 'mark'
  205. ) as PerformanceMark[]
  206. clearCM6Perf('dom')
  207. let lags = 0
  208. let nonLags = 0
  209. let longestLag = 0
  210. let totalKeypressCount = 0
  211. for (const entry of domUpdateEntries) {
  212. const keypressCount = entry.detail.keypressesSinceDomUpdateCount
  213. if (keypressCount === 1) {
  214. ++nonLags
  215. } else if (keypressCount > 1) {
  216. ++lags
  217. }
  218. if (keypressCount > longestLag) {
  219. longestLag = keypressCount
  220. }
  221. totalKeypressCount += keypressCount
  222. }
  223. const meanLagsPerMeasure = round(lags / (lags + nonLags), 4)
  224. const meanKeypressesPerMeasure = round(
  225. totalKeypressCount / (lags + nonLags),
  226. 4
  227. )
  228. // Get entries triggered by keystrokes
  229. const keypressPaintEntries = performance.getEntriesByName(
  230. TIMER_KEYPRESS_MEASURE_NAME,
  231. 'measure'
  232. ) as PerformanceMeasure[]
  233. const keypressPaintDurations = keypressPaintEntries.map(
  234. ({ duration }) => duration
  235. )
  236. const meanKeypressPaint = round(calculateMean(keypressPaintDurations), 2)
  237. clearCM6Perf('keypress')
  238. let longTasks = null
  239. // Get long task entries (Chromium-based browsers only at time of writing)
  240. if (performanceLongtaskSupported) {
  241. longTasks = longTaskSinceLastReportCount
  242. longTaskSinceLastReportCount = 0
  243. }
  244. const release = getMeta('ol-ExposedSettings')?.sentryRelease || null
  245. return {
  246. max,
  247. mean,
  248. median,
  249. ninetyFifthPercentile,
  250. maxUserEventsBetweenDomUpdates,
  251. docLength: latestDocLength,
  252. numberOfEntries: inputDurations.length,
  253. grammarly,
  254. sessionLength,
  255. memory,
  256. lags,
  257. nonLags,
  258. longestLag,
  259. meanLagsPerMeasure,
  260. meanKeypressesPerMeasure,
  261. meanKeypressPaint,
  262. longTasks,
  263. release,
  264. }
  265. }
  266. window._reportCM6Perf = () => {
  267. debugConsole.warn(reportCM6Perf())
  268. }