Coverage for plugin/protocol.py: 90.4%

206 statements  

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

1"""Transport-independent RPC, completion and operation state.""" 

2import copy 

3import time 

4import uuid 

5from datetime import datetime, timedelta, timezone 

6 

7from .contract import SCHEMA 

8from .schema import validator 

9 

10EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc) 

11 

12 

13def timestamp(seconds=None): 

14 # Epoch arithmetic avoids Windows' OSError for negative fromtimestamp() input. 

15 return (EPOCH + timedelta(seconds=time.time() if seconds is None else seconds)).isoformat( 

16 timespec='milliseconds').replace('+00:00', 'Z') 

17 

18 

19def epoch_seconds(text): 

20 """Seconds since the epoch of a timestamp() string.""" 

21 return (datetime.strptime(text, '%Y-%m-%dT%H:%M:%S.%fZ').replace(tzinfo=timezone.utc) - EPOCH).total_seconds() 

22 

23 

24class ApiError(Exception): 

25 def __init__(self, kind, message, details=None): 

26 super().__init__(message) 

27 self.kind = kind 

28 self.details = details 

29 

30 def record(self): 

31 data = {'type': self.kind} 

32 if self.details is not None: 

33 data['details'] = self.details 

34 return {'code': SCHEMA['x-errors'][self.kind], 'message': str(self), 'data': data} 

35 

36 

37def error_record(exception): 

38 if isinstance(exception, ApiError): 38 ↛ 40line 38 didn't jump to line 40 because the condition on line 38 was always true

39 return exception.record() 

40 return ApiError('internalError', 'Internal API error.').record() 

41 

42 

43class Deferred: 

44 """Callback completion; never runs a nested Qt event loop.""" 

45 def __init__(self): 

46 self.done = False 

47 self.value = None 

48 self.error = None 

49 self.callbacks = [] 

50 

51 def resolve(self, value=None, error=None): 

52 if self.done: 52 ↛ 53line 52 didn't jump to line 53 because the condition on line 52 was never true

53 return 

54 self.done, self.value, self.error = True, value, error 

55 callbacks, self.callbacks = self.callbacks, [] 

56 for callback in callbacks: 

57 callback(self) 

58 

59 def then(self, callback): 

60 if self.done: 

61 callback(self) 

62 else: 

63 self.callbacks.append(callback) 

64 return self 

65 

66 def map(self, callback): 

67 result = Deferred() 

68 def finish(source): 

69 if source.error: 

70 result.resolve(error=source.error) 

71 return 

72 try: 

73 value = callback(source.value) 

74 if isinstance(value, Deferred): 

75 value.then(lambda final: result.resolve(final.value, final.error)) 

76 else: 

77 result.resolve(value) 

78 except Exception as error: 

79 result.resolve(error=error) 

80 self.then(finish) 

81 return result 

82 

83 

84def completed(value=None, error=None): 

85 result = Deferred() 

86 result.resolve(value, error) 

87 return result 

88 

89 

90def settle(items): 

91 """Collect independent replies, preserving their request order.""" 

92 result = Deferred() 

93 values = [None] * len(items) 

94 remaining = [len(items)] 

95 if not items: 95 ↛ 96line 95 didn't jump to line 96 because the condition on line 95 was never true

96 return completed([]) 

97 def finish(index, source): 

98 values[index] = source.value 

99 remaining[0] -= 1 

100 if not remaining[0]: 

101 result.resolve(values) 

102 for index, item in enumerate(items): 

103 item.then(lambda source, index=index: finish(index, source)) 

104 return result 

105 

106 

107class Operations: 

108 def __init__(self, schedule, now=time.time): 

109 self.schedule = schedule 

110 self.now = now 

111 self.records = {} 

112 self.completions = {} 

113 self.cancellations = {} 

114 

115 def prune(self): 

116 limit = SCHEMA['x-limits'] 

117 terminal = sorted((record['updatedAt'], key) for key, record in self.records.items() 

118 if record['state'] in ('succeeded', 'failed', 'cancelled')) 

119 cutoff = timestamp(self.now() - limit['operationRetentionSeconds']) 

120 excess = max(0, len(terminal) - limit['maxRetainedOperations']) 

121 for index, (updated, key) in enumerate(terminal): 

122 if updated < cutoff or index < excess: 122 ↛ 123line 122 didn't jump to line 123 because the condition on line 122 was never true

123 self.records.pop(key, None) 

124 self.completions.pop(key, None) 

125 self.cancellations.pop(key, None) 

126 

127 def submit(self, method, session, start): 

128 self.prune() 

129 active = sum(not future.done for future in self.completions.values()) 

130 if active >= SCHEMA['x-limits']['maxActiveOperations']: 130 ↛ 131line 130 didn't jump to line 131 because the condition on line 130 was never true

131 raise ApiError('busy', 'Too many active operations.') 

132 key = uuid.uuid4().hex 

133 now = timestamp(self.now()) 

134 self.records[key] = {'operationId': key, 'method': method, 'session': session, 

135 'createdAt': now, 'updatedAt': now, 'state': 'queued', 

136 'cancellable': True, 'progress': None} 

137 future = self.completions[key] = Deferred() 

138 def finish(source): 

139 if not source.error and method in SCHEMA['x-methods']: 

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

141 schema = meta.get('operationResult', meta['result']) 

142 if not validator({**SCHEMA, 'oneOf': [schema]}).is_valid(source.value): 

143 source = completed(error=ApiError('internalError', 'Operation produced an invalid result.')) 

144 record = self.records[key] 

145 record.update(updatedAt=timestamp(self.now()), cancellable=False) 

146 if source.error: 

147 record['state'] = 'cancelled' if isinstance(source.error, ApiError) and source.error.kind == 'cancelled' else 'failed' 

148 record['error'] = error_record(source.error) 

149 else: 

150 record.update(state='succeeded', result=source.value) 

151 self.cancellations.pop(key, None) 

152 future.resolve(source.value, source.error) 

153 def run(): 

154 if future.done: 

155 return 

156 self.records[key].update(state='running', cancellable=False, updatedAt=timestamp(self.now())) 

157 try: 

158 pending = start(key) 

159 (pending if isinstance(pending, Deferred) else completed(pending)).then(finish) 

160 except Exception as error: 

161 finish(completed(error=error)) 

162 self.schedule(run) 

163 return {'operationId': key, 'method': method, 'session': session} 

164 

165 def get(self, key): 

166 self.prune() 

167 if key not in self.records: 167 ↛ 168line 167 didn't jump to line 168 because the condition on line 167 was never true

168 raise ApiError('notFound', 'Operation not found.') 

169 return copy.deepcopy(self.records[key]) 

170 

171 def cancel(self, key): 

172 record = self.get(key) 

173 if self.completions[key].done: 173 ↛ 174line 173 didn't jump to line 174 because the condition on line 173 was never true

174 return {'requested': False} 

175 if record['state'] == 'queued': 

176 error = ApiError('cancelled', 'Operation cancelled before execution.') 

177 self.records[key].update(state='cancelled', error=error.record(), cancellable=False, 

178 updatedAt=timestamp(self.now())) 

179 self.completions[key].resolve(error=error) 

180 elif key in self.cancellations: 180 ↛ 183line 180 didn't jump to line 183 because the condition on line 180 was always true

181 self.cancellations[key]() 

182 else: 

183 raise ApiError('unsupportedCapability', 'This operation cannot be cancelled.') 

184 return {'requested': True} 

185 

186 

187class Dispatcher: 

188 def __init__(self, runtime): 

189 self.runtime = runtime 

190 self.validators = {name: validator({**SCHEMA, 'oneOf': [meta['params']]}) 

191 for name, meta in SCHEMA['x-methods'].items()} 

192 

193 def params(self, method, params): 

194 if method not in self.validators: 194 ↛ 195line 194 didn't jump to line 195 because the condition on line 194 was never true

195 raise ApiError('methodNotFound', 'Unknown method: ' + method) 

196 errors = sorted(self.validators[method].iter_errors(params), key=lambda e: str(list(e.path))) 

197 if errors: 

198 raise ApiError('invalidParams', errors[0].message, 

199 {'path': '/' + '/'.join(str(part) for part in errors[0].path)}) 

200 result = copy.deepcopy(params) 

201 definition = SCHEMA['$defs'][SCHEMA['x-methods'][method]['params']['$ref'].split('/')[-1]] 

202 for key, value in definition['properties'].items(): 

203 if key not in result and 'default' in value: 

204 result[key] = copy.deepcopy(value['default']) 

205 return result 

206 

207 def invoke(self, method, params): 

208 return self.runtime.invoke(method, self.params(method, params)) 

209 

210 def request(self, request, context=None): 

211 context = context or {} 

212 if isinstance(request, list): 

213 if not request or len(request) > SCHEMA['x-limits']['maxBatchItems']: 213 ↛ 214line 213 didn't jump to line 214 because the condition on line 213 was never true

214 return completed(self.reply(None, error=ApiError('invalidRequest', 'Invalid batch.'))) 

215 return settle([self.request(item, context) if isinstance(item, dict) else 

216 completed(self.reply(None, error=ApiError('invalidRequest', 'Batch items must be request objects.'))) 

217 for item in request]).map( 

218 lambda replies: [reply for reply in replies if reply is not None] or None) 

219 request_id = None 

220 notification = False 

221 started = time.monotonic() 

222 def log(error=None): 

223 owner = getattr(self.runtime, 'owner', None) 

224 if owner: 

225 owner.logEvent('rpc', {'method': request.get('method') if isinstance(request, dict) else None, 

226 'id': request_id, 'durationMs': round((time.monotonic() - started) * 1000), 

227 'error': error.kind if isinstance(error, ApiError) else 'internalError' if error else None}) 

228 try: 

229 if not isinstance(request, dict) or request.get('jsonrpc') != '2.0' or not isinstance(request.get('method'), str) or not request['method']: 229 ↛ 230line 229 didn't jump to line 230 because the condition on line 229 was never true

230 raise ApiError('invalidRequest', 'Invalid JSON-RPC request.') 

231 if set(request) - {'jsonrpc', 'id', 'method', 'params'}: 231 ↛ 232line 231 didn't jump to line 232 because the condition on line 231 was never true

232 raise ApiError('invalidRequest', 'Unknown request property.') 

233 candidate_id = request.get('id') 

234 if candidate_id is not None and type(candidate_id) not in (str, int): 

235 raise ApiError('invalidRequest', 'Invalid request ID.') 

236 request_id = candidate_id 

237 notification = 'id' not in request 

238 method = request['method'] 

239 params = self.params(method, request.get('params', {})) 

240 if notification and SCHEMA['x-methods'][method]['effect'] != 'read': 

241 log(ApiError('invalidParams', 'Side effects require a request ID.')) 

242 return completed(None) 

243 if method == 'access.requestPermission': 

244 pending = self.runtime.permission(context) 

245 else: 

246 pending = self.runtime.invoke(method, params) 

247 pending = pending if isinstance(pending, Deferred) else completed(pending) 

248 result = Deferred() 

249 def finish(source): 

250 log(source.error) 

251 result.resolve(None if notification else self.reply(request_id, source.value, source.error)) 

252 pending.then(finish) 

253 return result 

254 except Exception as error: 

255 log(error) 

256 return completed(None if notification else self.reply(request_id, error=error)) 

257 

258 @staticmethod 

259 def reply(request_id, value=None, error=None): 

260 return {'jsonrpc': '2.0', 'id': request_id, 

261 **({'error': error_record(error)} if error else {'result': value})}