Coverage for plugin/runtime.py: 87.7%

313 statements  

« prev     ^ index     » next       coverage.py v7.17.5, created at 2026-11-28 02:31 +0000

1"""Shared dispatcher, Qt admission and serialized native operation completion.""" 

2import base64 

3import copy 

4import hashlib 

5import json 

6import time 

7import uuid 

8 

9import aqt 

10 

11from . import compat, util 

12from .contract import SCHEMA 

13from .gui import Gui 

14from .media import MediaTransaction 

15from .protocol import ApiError, Deferred, Dispatcher, Operations, completed, error_record 

16from .services import Services 

17 

18LIFECYCLE_BUSY = 'Collection lifecycle operation is active.' 

19OPERATION_BUSY = 'A collection operation is active.' 

20# Prediction/conversion tokens and search cursors expire after this long. 

21SNAPSHOT_SECONDS = 600 

22TOKEN_LIMIT = 1000 

23CURSOR_LIMIT = 100 

24SNAPSHOT_ID_LIMIT = 1000000 

25# Polling delay for work that waits for active collection operations. 

26POLL_MILLISECONDS = 25 

27 

28GUI_METHODS = {'collection.refresh', 'collection.sync', 'profiles.list', 'profiles.getActive', 

29 'profiles.switch', 'application.navigate', 'application.exit', 'application.importFile'} 

30GUI_METHODS.update(name for name in SCHEMA['x-methods'] if name.startswith(('browser.', 'editors.', 'reviewer.'))) 

31 

32# Collection paths each method needs; "a|b" accepts either name. Scheduler paths 

33# such as sched.build_answer exist only while the v3 scheduler is active. 

34NATIVE_REQUIREMENTS = { 

35 'notes.create': ('add_note', '_backend.render_uncommitted_card_legacy|_backend.render_uncommitted_card|findTemplates'), 

36 'notes.createMany': ('add_note', '_backend.render_uncommitted_card_legacy|_backend.render_uncommitted_card|findTemplates'), 

37 'notes.validate': ('_backend.render_uncommitted_card_legacy|_backend.render_uncommitted_card|findTemplates',), 

38 'notes.update': ('update_note',), 

39 'cards.move': ('set_deck',), 

40 'scheduling.getQueue': ('sched.get_queued_cards',), 

41 'scheduling.predict': ('_backend.get_scheduling_states|_backend.get_next_card_states', 

42 '_backend.describe_next_states', 'sched.build_answer'), 

43 'scheduling.answer': ('sched.build_answer', 'sched.answer_card'), 

44 'scheduling.answerMany': ('sched.build_answer', 'sched.answer_card'), 

45 'scheduling.repositionNewCards': ('sched.reposition_new_cards',), 

46 'scheduling.setDueDate': ('sched.set_due_date',), 

47 'deckPresets.get': ('_backend.get_deck_config',), 

48 'deckPresets.create': ('decks.get_deck_configs_for_update', 'decks.update_deck_configs'), 

49 'deckPresets.update': ('decks.get_deck_configs_for_update', 'decks.update_deck_configs'), 

50 'deckPresets.assign': ('decks.get_deck_configs_for_update', 'decks.update_deck_configs'), 

51 'deckPresets.delete': ('decks.get_deck_configs_for_update', 'decks.update_deck_configs'), 

52 'media.store': ('media.write_data', 'media.trash_files'), 

53 'collection.checkIntegrity': ('fix_integrity',), 

54 'collection.undo': ('undo', 'undo_status'), 

55 # Before 2.1.28 Python synced over HTTP itself; there is no backend sync to drive. 

56 'collection.sync': ('_backend.sync_collection',), 

57} 

58REQUIREMENT_REASONS = { 

59 '_backend.sync_collection': 'Requires the native sync of Anki 2.1.28 or later.', 

60} 

61# Release features without a collection path; see compat.FEATURES. 

62FEATURE_REQUIREMENTS = { 

63 'editors.openNote': ('editorDialog',), 

64 'application.importFile': ('importDialog',), 

65} 

66 

67 

68def clear_editor_history(): 

69 if compat.editor_dialog_available(): 69 ↛ exitline 69 didn't return from function 'clear_editor_history' because the condition on line 69 was always true

70 from .edit import history 

71 history.note_ids.clear() 

72 

73 

74class Runtime: 

75 def __init__(self, owner, schedule=None): 

76 from aqt.qt import QTimer 

77 self.owner = owner 

78 self.schedule = schedule or (lambda callback: QTimer.singleShot(0, callback)) 

79 self.schedule_later = lambda callback: QTimer.singleShot(POLL_MILLISECONDS, callback) 

80 self.operations = Operations(self.schedule) 

81 self.dispatcher = Dispatcher(self) 

82 self.gui = Gui(self) 

83 self._collection = None 

84 self._session = None 

85 self.profile_name = None 

86 self.tokens = {} 

87 self.cursors = {} 

88 self.generation = 0 

89 self.exit_requested = False 

90 self.full_reset_required = False 

91 self.active_reviewer_card = None 

92 self.lifecycle_active = False 

93 self.media_recovered_session = None 

94 

95 @property 

96 def mw(self): 

97 return aqt.mw 

98 

99 @property 

100 def session(self): 

101 col = self.mw.col if self.mw else None 

102 if col is not self._collection: 

103 self.clear_session_state() 

104 self._collection = col 

105 self._session = uuid.uuid4().hex if col else None 

106 self.profile_name = self.mw.pm.name if col else None 

107 return self._session 

108 

109 def invalidate_session(self, *args): 

110 self._collection = None 

111 self._session = None 

112 self.clear_session_state() 

113 

114 def clear_session_state(self): 

115 """Forget everything bound to the previous collection session.""" 

116 self.tokens.clear() 

117 self.cursors.clear() 

118 self.gui.editors.clear() 

119 clear_editor_history() 

120 

121 def register_hooks(self): 

122 compat.gui_hook('profile_will_close').append(self.invalidate_session) 

123 compat.register_collection_close(self.invalidate_session) 

124 

125 def service(self): 

126 return Services(self, *self.capture()) 

127 

128 def capture(self, expected=None): 

129 session = self.session 

130 if session is None: 

131 raise ApiError('collectionUnavailable', 'Collection is not available.') 

132 if expected is not None and expected != session: 132 ↛ 133line 132 didn't jump to line 133 because the condition on line 132 was never true

133 raise ApiError('staleSession', 'Collection session changed.') 

134 return self._collection, session 

135 

136 def invalidate_predictions(self): 

137 self.generation += 1 

138 

139 @staticmethod 

140 def digest(value): 

141 return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest() 

142 

143 def token(self, kind, value): 

144 if len(self.tokens) >= TOKEN_LIMIT: 144 ↛ 145line 144 didn't jump to line 145 because the condition on line 144 was never true

145 oldest = min(self.tokens, key=lambda key: self.tokens[key][3]) 

146 self.tokens.pop(oldest) 

147 key = uuid.uuid4().hex 

148 self.tokens[key] = (kind, self.digest(value), self._session, time.monotonic()) 

149 return key 

150 

151 def check_token(self, key, kind, value): 

152 token = self.tokens.get(key) 

153 if not token or token[:3] != (kind, self.digest(value), self._session) or time.monotonic() - token[3] > SNAPSHOT_SECONDS: 153 ↛ 154line 153 didn't jump to line 154 because the condition on line 153 was never true

154 raise ApiError('conflict', 'Prediction/conversion token is stale.') 

155 

156 def page(self, ids, method, params, session): 

157 params = dict(params) 

158 cursor = params.pop('cursor', None) 

159 limit = params.get('limit', 100) 

160 now = time.monotonic() 

161 self.cursors = {key: value for key, value in self.cursors.items() if now - value['created'] <= SNAPSHOT_SECONDS} 

162 if cursor: 

163 state = self.cursors.get(cursor) 

164 if not state or state['session'] != session: 

165 raise ApiError('staleCursor', 'Cursor expired or collection changed.') 

166 if state['method'] != method or state['params'] != params: 

167 raise ApiError('invalidParams', 'Cursor query parameters changed.') 

168 self.cursors.pop(cursor) 

169 else: 

170 if len(self.cursors) >= CURSOR_LIMIT or len(ids) > SNAPSHOT_ID_LIMIT: 

171 raise ApiError('busy', 'Search snapshot capacity exceeded.') 

172 state = {'ids': ids, 'offset': 0, 'created': now, 'session': session, 'method': method, 'params': params} 

173 start = state['offset'] 

174 selected = state['ids'][start:start + limit] 

175 next_offset = start + limit 

176 if next_offset < len(state['ids']): 

177 next_cursor = uuid.uuid4().hex 

178 self.cursors[next_cursor] = {**state, 'offset': next_offset} 

179 else: 

180 next_cursor = None 

181 if method in ('notes.search', 'notes.findEmpty'): 

182 selected = [id for id in selected if self._collection.db.scalar('select 1 from notes where id=?', id)] 

183 elif method == 'cards.search': 

184 selected = [id for id in selected if self._collection.db.scalar('select 1 from cards where id=?', id)] 

185 return {'ids': [str(id) for id in selected], 'nextCursor': next_cursor} 

186 

187 def capability_reason(self, method, col=None): 

188 if method in ('api.describe', 'api.execute', 'operations.get', 'operations.cancel', 'access.requestPermission', 'media.store'): 

189 handler = True 

190 else: 

191 adapter = self.gui if method in GUI_METHODS else Services 

192 handler = callable(getattr(adapter, method.replace('.', '_'), None)) 

193 if not handler: 193 ↛ 194line 193 didn't jump to line 194 because the condition on line 193 was never true

194 return 'No adapter for ' + method 

195 for name in FEATURE_REQUIREMENTS.get(method, ()): 

196 reason = compat.missing_feature(name) 

197 if reason: 197 ↛ 198line 197 didn't jump to line 198 because the condition on line 197 was never true

198 return reason 

199 if col is None: 

200 col = self.mw.col if self.mw else None 

201 if col: 

202 for path in NATIVE_REQUIREMENTS.get(method, ()): 

203 if not any(callable(compat.lookup(col, choice)) for choice in path.split('|')): 

204 if path.startswith('sched.') and hasattr(col, 'v3_scheduler') and not col.v3_scheduler(): 

205 return 'Requires the v3 scheduler; enable it in Anki preferences.' 

206 if path.startswith('sched.') and not hasattr(col, 'v3_scheduler'): 206 ↛ 207line 206 didn't jump to line 207 because the condition on line 206 was never true

207 return 'Requires the v3 scheduler of Anki 2.1.45 or later.' 

208 return REQUIREMENT_REASONS.get(path, 'Native capability missing: ' + path) 

209 return None 

210 

211 def require_capability(self, method): 

212 reason = self.capability_reason(method) 

213 if reason: 

214 raise ApiError('unsupportedCapability', reason) 

215 

216 def describe(self): 

217 methods = [] 

218 for name in SCHEMA['x-methods']: 

219 reason = self.capability_reason(name) 

220 methods.append({'name': name, 'available': reason is None, 'reason': reason}) 

221 return {'apiMajor': 1, 'ankiVersion': aqt.appVersion, 'schema': copy.deepcopy(SCHEMA), 

222 'methods': methods, 'limits': copy.deepcopy(SCHEMA['x-limits'])} 

223 

224 def finish_changes(self, service, initiator=None): 

225 changes, service.changes = service.changes, [] 

226 legacy = [change for change in changes if isinstance(change, compat.LegacyChanges)] 

227 # Untracked changes refresh every screen, so one notification covers them all. 

228 for change in [change for change in changes if not isinstance(change, compat.LegacyChanges)] + legacy[:1]: 

229 compat.on_op_finished(self.mw, change, initiator) 

230 if self.full_reset_required: 

231 self.full_reset_required = False 

232 self.mw.reset() 

233 

234 def direct(self, method, params): 

235 meta = SCHEMA['x-methods'][method] 

236 if method in GUI_METHODS: 

237 if meta['scope'] == 'collection': 

238 self.capture(params.get('session')) 

239 return self.gui.execute(method, params) 

240 service = self.service() 

241 if self.lifecycle_active: 

242 raise ApiError('busy', LIFECYCLE_BUSY) 

243 if meta['effect'] in ('write', 'advancedWrite'): 

244 self.gui.guard(method, params) 

245 try: 

246 return service.execute(method, params) 

247 finally: 

248 self.finish_changes(service) 

249 

250 def background(self, work, expected=None, after=None, initiator=None): 

251 col, session = self.capture(expected) 

252 service = Services(self, col, session) 

253 result = Deferred() 

254 # A GUI/background operation could otherwise unload the captured collection. 

255 compat.increase_background_ops(self.mw) 

256 reviewer = self.mw.reviewer 

257 self.active_reviewer_card = reviewer.card.id if reviewer and reviewer.card and self.mw.state == 'review' else None 

258 def task(): 

259 if self._collection is not col or self._session != session: 

260 raise ApiError('staleSession', 'Collection changed before execution.') 

261 # Restore interrupted journals before a session's first collection work. 

262 if self.media_recovered_session != session: 

263 self.media_recovered_session = session 

264 MediaTransaction.recover(service) 

265 return work(service) 

266 def finished(future): 

267 compat.decrease_background_ops(self.mw) 

268 try: 

269 value = future.result() 

270 if after: 

271 value = after(value) 

272 self.finish_changes(service, initiator) 

273 result.resolve(value) 

274 except Exception as error: 

275 # Successful prefixes still need post-write notification on failure. 

276 try: 

277 self.finish_changes(service, initiator) 

278 finally: 

279 result.resolve(error=error) 

280 compat.run_in_background(self.mw, task, finished) 

281 return result 

282 

283 def invoke(self, method, params): 

284 self.require_capability(method) 

285 if method == 'api.describe': 

286 return completed(self.describe()) 

287 if method == 'operations.get': 

288 return completed(self.operations.get(params['operationId'])) 

289 if method == 'operations.cancel': 

290 return completed(self.operations.cancel(params['operationId'])) 

291 if method == 'api.execute': 

292 session = self.session 

293 for command in params['commands']: 

294 if command['method'] in ('api.execute', 'application.exit', 'profiles.switch'): 294 ↛ 295line 294 didn't jump to line 295 because the condition on line 294 was never true

295 raise ApiError('invalidParams', 'This command is not allowed inside api.execute.') 

296 self.dispatcher.params(command['method'], command.get('params', {})) 

297 return completed(self.operations.submit(method, session, lambda key: self.execute_commands(params['commands'], session, key))) 

298 meta = SCHEMA['x-methods'][method] 

299 if self.lifecycle_active and meta['scope'] == 'collection': 299 ↛ 300line 299 didn't jump to line 300 because the condition on line 299 was never true

300 raise ApiError('busy', LIFECYCLE_BUSY) 

301 if meta['scope'] == 'collection': 

302 _, session = self.capture(params.get('session')) 

303 else: 

304 session = self.session 

305 if meta['effect'] in ('write', 'advancedWrite'): 

306 self.gui.guard(method, params) 

307 if method in GUI_METHODS and meta['scope'] == 'collection' and compat.background_op_count(self.mw): 307 ↛ 308line 307 didn't jump to line 308 because the condition on line 307 was never true

308 raise ApiError('busy', OPERATION_BUSY) 

309 def start(key=None): 

310 self.require_capability(method) 

311 if self.lifecycle_active and (meta['scope'] == 'collection' or meta['effect'] == 'lifecycle'): 311 ↛ 312line 311 didn't jump to line 312 because the condition on line 311 was never true

312 raise ApiError('busy', LIFECYCLE_BUSY) 

313 if meta['effect'] in ('write', 'advancedWrite'): 

314 self.gui.guard(method, params) 

315 if meta['scope'] == 'collection': 

316 self.capture(session) 

317 if method in GUI_METHODS and compat.background_op_count(self.mw): 

318 raise ApiError('busy', OPERATION_BUSY) 

319 if method in GUI_METHODS: 

320 value = self.gui.execute(method, params, operation_id=key) 

321 return value if isinstance(value, Deferred) else completed(value) 

322 if method == 'media.store': 

323 return self.acquire_media(params, session) 

324 return self.background(lambda service: service.execute(method, params), session) 

325 if meta['completion'] == 'operation': 

326 return completed(self.operations.submit(method, session, start)) 

327 return start() 

328 

329 def await_value(self, future): 

330 def resolve(value): 

331 if isinstance(value, dict) and 'operationId' in value and value.get('method') in SCHEMA['x-methods']: 

332 return self.operations.completions[value['operationId']] 

333 return value 

334 return future.map(resolve) 

335 

336 def execute_commands(self, commands, session, operation_id=None): 

337 result = Deferred() 

338 items = [] 

339 cancelled = [False] 

340 if operation_id: 340 ↛ 343line 340 didn't jump to line 343 because the condition on line 340 was always true

341 self.operations.cancellations[operation_id] = lambda: cancelled.__setitem__(0, True) 

342 self.operations.records[operation_id]['cancellable'] = True 

343 def step(index): 

344 if cancelled[0]: 

345 result.resolve(error=ApiError('cancelled', 'Sequence cancelled between commands.', {'items': items})) 

346 return 

347 if index == len(commands): 

348 result.resolve({'items': items}) 

349 return 

350 command = commands[index] 

351 name = command['method'] 

352 try: 

353 params = dict(command.get('params', {})) 

354 if SCHEMA['x-methods'][name]['scope'] == 'collection': 354 ↛ 356line 354 didn't jump to line 356 because the condition on line 354 was always true

355 params.setdefault('session', session) 

356 pending = self.await_value(self.dispatcher.invoke(name, params)) 

357 except Exception as error: 

358 pending = completed(error=error) 

359 def finish(source): 

360 items.append({'index': index, 'method': name, **({'error': error_record(source.error)} if source.error else {'result': source.value})}) 

361 self.schedule(lambda: step(index + 1)) 

362 pending.then(finish) 

363 step(0) 

364 return result 

365 

366 def acquire_media(self, params, session): 

367 result = Deferred() 

368 limit = SCHEMA['x-limits']['maxMediaBytes'] 

369 source = params['source'] 

370 def read(): 

371 if 'data' in source: 

372 return base64.b64decode(source['data'], validate=True) 

373 if 'path' in source: 373 ↛ 378line 373 didn't jump to line 378 because the condition on line 373 was always true

374 with open(source['path'], 'rb') as file: 

375 return file.read(limit + 1) 

376 # Anki's HTTP client applies the configured timeout. Limit acquisition, 

377 # including HTTP redirects, before any native media mutation. 

378 return util.download(source['url'], limit) 

379 def done(future): 

380 try: 

381 data = future.result() 

382 if len(data) > limit: 382 ↛ 383line 382 didn't jump to line 383 because the condition on line 382 was never true

383 raise ApiError('invalidParams', 'Media exceeds the configured size limit.') 

384 self.capture(session) 

385 self.background(lambda service: service.store_bytes(params['filename'], data, params.get('collision', 'rename'), params.get('skipIfHash')), session).then(lambda source: result.resolve(source.value, source.error)) 

386 except Exception as error: 

387 result.resolve(error=error if isinstance(error, ApiError) else ApiError('ioError', str(error))) 

388 compat.run_in_background(self.mw, read, done, uses_collection=False) 

389 return result 

390 

391 def permission(self, context): 

392 # The facade owns the persisted user-facing permission flow, shared by both APIs. 

393 value = self.owner.permission(context.get('origin', ''), context.get('allowed', False)) 

394 pending = value if isinstance(value, Deferred) else completed(value) 

395 return pending.map(lambda value: {'permission': value['permission'], 'requireApiKey': bool(util.setting('apiKey'))})