sg-python-api 0.1.2__py3-none-any.whl → 0.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (56) hide show
  1. {sg_python_api-0.1.2.dist-info → sg_python_api-0.2.0.dist-info}/METADATA +21 -24
  2. sg_python_api-0.2.0.dist-info/RECORD +58 -0
  3. shotgun_api3/__init__.py +4 -0
  4. shotgun_api3/_async_client.py +347 -281
  5. shotgun_api3/_async_driver.py +25 -55
  6. shotgun_api3/_async_httpx2.py +92 -59
  7. shotgun_api3/_async_transport.py +38 -3
  8. shotgun_api3/_capabilities.py +4 -3
  9. shotgun_api3/_client.py +296 -422
  10. shotgun_api3/_config.py +245 -120
  11. shotgun_api3/_connections.py +144 -0
  12. shotgun_api3/_crud.py +25 -250
  13. shotgun_api3/_driver.py +29 -54
  14. shotgun_api3/_execution.py +1 -3
  15. shotgun_api3/_files.py +193 -21
  16. shotgun_api3/_methods.py +59 -411
  17. shotgun_api3/_protocol.py +27 -53
  18. shotgun_api3/_transport.py +82 -407
  19. shotgun_api3/_version.py +7 -2
  20. shotgun_api3/lib/mockgun/__init__.py +20 -7
  21. shotgun_api3/lib/mockgun/_activity.py +510 -0
  22. shotgun_api3/lib/mockgun/_async_client.py +196 -0
  23. shotgun_api3/lib/mockgun/_dates.py +164 -0
  24. shotgun_api3/lib/mockgun/_errors.py +18 -0
  25. shotgun_api3/lib/mockgun/_events.py +1031 -0
  26. shotgun_api3/lib/mockgun/_follows.py +217 -0
  27. shotgun_api3/lib/mockgun/_handlers.py +558 -0
  28. shotgun_api3/lib/mockgun/_links.py +440 -0
  29. shotgun_api3/lib/mockgun/_new_client.py +92 -0
  30. shotgun_api3/lib/mockgun/_presets.py +492 -0
  31. shotgun_api3/lib/mockgun/_query.py +2163 -0
  32. shotgun_api3/lib/mockgun/_retirement.py +368 -0
  33. shotgun_api3/lib/mockgun/_schema.py +172 -0
  34. shotgun_api3/lib/mockgun/_schema_writes.py +425 -0
  35. shotgun_api3/lib/mockgun/_search.py +378 -0
  36. shotgun_api3/lib/mockgun/_server.py +169 -0
  37. shotgun_api3/lib/mockgun/_sessions.py +206 -0
  38. shotgun_api3/lib/mockgun/_site.py +150 -0
  39. shotgun_api3/lib/mockgun/_site_data.py +584 -0
  40. shotgun_api3/lib/mockgun/_storage.py +208 -0
  41. shotgun_api3/lib/mockgun/_store.py +1446 -0
  42. shotgun_api3/lib/mockgun/_summaries.py +964 -0
  43. shotgun_api3/lib/mockgun/_sync_client.py +190 -0
  44. shotgun_api3/lib/mockgun/_threads.py +226 -0
  45. shotgun_api3/lib/mockgun/_thumbnails.py +146 -0
  46. shotgun_api3/lib/mockgun/_transport.py +145 -0
  47. shotgun_api3/lib/mockgun/_uploads.py +417 -0
  48. shotgun_api3/lib/mockgun/_wire.py +120 -0
  49. shotgun_api3/lib/mockgun/mockgun.py +14 -0
  50. shotgun_api3/lib/sgtimezone.py +24 -1
  51. sg_python_api-0.1.2.dist-info/RECORD +0 -31
  52. shotgun_api3/_signatures.py +0 -53
  53. shotgun_api3/lib/mockgun/_async.py +0 -315
  54. shotgun_api3/lib/mockgun/_mockgun.py +0 -1666
  55. {sg_python_api-0.1.2.dist-info → sg_python_api-0.2.0.dist-info}/WHEEL +0 -0
  56. {sg_python_api-0.1.2.dist-info → sg_python_api-0.2.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,558 @@
1
+ """Dispatch the RPC methods currently emulated by the fake site."""
2
+
3
+ from collections.abc import Callable
4
+ from copy import deepcopy
5
+ from typing import TYPE_CHECKING, TypeAlias, cast
6
+
7
+ from . import _site_data
8
+ from ._activity import (
9
+ read_stream,
10
+ record_create_activity,
11
+ record_lifecycle_activity,
12
+ record_update_activity,
13
+ taint_activity,
14
+ )
15
+ from ._errors import MockgunError, ServerFaultError
16
+ from ._events import record_create, record_lifecycle, record_schema_write, record_update
17
+ from ._follows import follow, follow_created_note, followers, following, unfollow
18
+ from ._query import ReadScope, page, project_rows, select
19
+ from ._retirement import kept_members, retire, revive
20
+ from ._schema_writes import create_field, delete_field, update_field
21
+ from ._search import search
22
+ from ._sessions import RequestContext
23
+ from ._store import CONNECTION_FIELDS
24
+ from ._summaries import summarize
25
+ from ._threads import read_thread
26
+ from ._wire import RpcCall
27
+
28
+ if TYPE_CHECKING:
29
+ from ._server import FakeServer
30
+ from ._store import FieldValue
31
+
32
+ _Handler: TypeAlias = Callable[['FakeServer', RpcCall, RequestContext], object]
33
+ HANDLERS: dict[str, _Handler] = {}
34
+ UNWRAPPED_METHODS: set[str] = set()
35
+ _CONNECTION_ENDPOINTS = {
36
+ entity_type: frozenset({'id', side_a, side_b})
37
+ for entity_type, side_a, side_b in CONNECTION_FIELDS.values()
38
+ }
39
+
40
+
41
+ def _check_connection_path(entity_type: str, path: str, allowed: frozenset[str]) -> None:
42
+ """Reject a path whose first segment is outside a connection's surface."""
43
+ if path.split('.', 1)[0] not in allowed:
44
+ raise MockgunError(f'mockgun cannot read {entity_type}.{path}')
45
+
46
+
47
+ def _check_connection_tree(
48
+ entity_type: str, tree: dict[str, object], allowed: frozenset[str]
49
+ ) -> None:
50
+ """Check all filter paths, including nested filter groups."""
51
+ for condition in cast('list[dict[str, object]]', tree.get('conditions', [])):
52
+ if 'path' in condition:
53
+ _check_connection_path(entity_type, cast('str', condition['path']), allowed)
54
+ elif 'conditions' in condition:
55
+ _check_connection_tree(entity_type, condition, allowed)
56
+
57
+
58
+ def _check_connection_read(
59
+ entity_type: str,
60
+ return_fields: list[str],
61
+ filters: dict[str, object],
62
+ order: list[dict[str, str]],
63
+ ) -> None:
64
+ """Reject paths outside the observed identity and endpoint surface."""
65
+ if not entity_type.endswith('Connection'):
66
+ return
67
+ allowed = _CONNECTION_ENDPOINTS.get(entity_type)
68
+ if allowed is None:
69
+ raise MockgunError(f'mockgun cannot read unmodeled {entity_type}')
70
+ for path in return_fields:
71
+ _check_connection_path(entity_type, path, allowed)
72
+ _check_connection_tree(entity_type, filters, allowed)
73
+ for entry in order:
74
+ _check_connection_path(entity_type, entry['field_name'], allowed)
75
+
76
+
77
+ def _check_event_write(server: 'FakeServer', entity_type: str) -> None:
78
+ """Reject direct event mutation once event identities and contents are unknown."""
79
+ if entity_type == 'EventLogEntry' and server.store.events_unknown is not None:
80
+ raise MockgunError(f'EventLogEntry is unknown: {server.store.events_unknown}')
81
+
82
+
83
+ def _fields(params: dict[str, object]) -> tuple[dict[str, object], dict[str, str]]:
84
+ """Split wire field entries into values and per-field update modes."""
85
+ fields: dict[str, object] = {}
86
+ modes: dict[str, str] = {}
87
+ for entry in cast('list[dict[str, object]]', params['fields']):
88
+ name = cast('str', entry['field_name'])
89
+ fields[name] = entry['value']
90
+ if 'multi_entity_update_mode' in entry:
91
+ modes[name] = cast('str', entry['multi_entity_update_mode'])
92
+ return fields, modes
93
+
94
+
95
+ def _follow_params(
96
+ method: str, raw: object, required: tuple[str, ...], optional: tuple[str, ...] = ()
97
+ ) -> dict[str, object]:
98
+ """Check the exact JSON object accepted by one follow RPC."""
99
+ if not isinstance(raw, dict):
100
+ raise MockgunError(f'mockgun cannot {method} parameter params: expected object')
101
+ params = cast('dict[str, object]', raw)
102
+ missing = set(required) - params.keys()
103
+ if missing:
104
+ raise MockgunError(f'mockgun cannot {method} parameter {min(missing)}: missing')
105
+ extra = params.keys() - set(required) - set(optional)
106
+ if extra:
107
+ raise MockgunError(f'mockgun cannot {method} parameter {min(extra)}: unexpected')
108
+ for key, value in params.items():
109
+ valid = isinstance(value, str) if key == 'entity_type' else isinstance(value, dict)
110
+ if not valid:
111
+ raise MockgunError(f'mockgun cannot {method} parameter {key}: wrong JSON type')
112
+ return params
113
+
114
+
115
+ def _register(name: str, *, wrapped: bool = True) -> Callable[[_Handler], _Handler]:
116
+ """Register one handler under its wire method name."""
117
+
118
+ def decorate(handler: _Handler) -> _Handler:
119
+ HANDLERS[name] = handler
120
+ if not wrapped:
121
+ UNWRAPPED_METHODS.add(name)
122
+ return handler
123
+
124
+ return decorate
125
+
126
+
127
+ @_register('export_page')
128
+ def _export_page(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
129
+ """Dispatch validated export_page site data parameters."""
130
+ return _site_data.export_page(server, call.params, context=context)
131
+
132
+
133
+ @_register('nav_expand', wrapped=False)
134
+ def _nav_expand(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
135
+ """Dispatch validated nav_expand site data parameters."""
136
+ return _site_data.nav_expand(server, call.params, context=context)
137
+
138
+
139
+ @_register('nav_search', wrapped=False)
140
+ def _nav_search(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
141
+ """Dispatch validated nav_search site data parameters."""
142
+ return _site_data.nav_search(server, call.params, context=context)
143
+
144
+
145
+ @_register('preferences_read', wrapped=False)
146
+ def _preferences_read(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
147
+ """Dispatch validated preferences_read site data parameters."""
148
+ return _site_data.preferences_read(server, call.params, context=context)
149
+
150
+
151
+ def _schema_project_id(params: object) -> int | None:
152
+ """Extract a Project ID from optional schema-read parameters."""
153
+ if not isinstance(params, dict):
154
+ return None
155
+ project = cast('dict[str, object]', params).get('project')
156
+ if not isinstance(project, dict):
157
+ return None
158
+ link = cast('dict[str, object]', project)
159
+ identity = link.get('id')
160
+ return (
161
+ identity
162
+ if link.get('type') == 'Project'
163
+ and isinstance(identity, int)
164
+ and not isinstance(identity, bool)
165
+ else None
166
+ )
167
+
168
+
169
+ @_register('user_subscriptions_read')
170
+ def _user_subscriptions_read(
171
+ server: 'FakeServer', call: RpcCall, context: RequestContext
172
+ ) -> object:
173
+ """Dispatch validated user_subscriptions_read site data parameters."""
174
+ return _site_data.user_subscriptions_read(server, call.params, context=context)
175
+
176
+
177
+ @_register('user_subscriptions_create')
178
+ def _user_subscriptions_create(
179
+ server: 'FakeServer', call: RpcCall, context: RequestContext
180
+ ) -> object:
181
+ """Dispatch validated user_subscriptions_create site data parameters."""
182
+ return _site_data.user_subscriptions_create(server, call.params, context=context)
183
+
184
+
185
+ @_register('update_project_last_accessed_by_current_user')
186
+ def _update_project_last_accessed_by_current_user(
187
+ server: 'FakeServer', call: RpcCall, context: RequestContext
188
+ ) -> object:
189
+ """Dispatch validated update_project_last_accessed_by_current_user site data parameters."""
190
+ return _site_data.update_project_last_accessed_by_current_user(
191
+ server, call.params, context=context
192
+ )
193
+
194
+
195
+ @_register('work_schedule_read')
196
+ def _work_schedule_read(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
197
+ """Dispatch validated work_schedule_read site data parameters."""
198
+ return _site_data.work_schedule_read(server, call.params, context=context)
199
+
200
+
201
+ @_register('work_schedule_update')
202
+ def _work_schedule_update(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
203
+ """Dispatch validated work_schedule_update site data parameters."""
204
+ return _site_data.work_schedule_update(server, call.params, context=context)
205
+
206
+
207
+ @_register('activity_stream', wrapped=False)
208
+ def _activity_stream(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
209
+ """Return the unwrapped observed activity view."""
210
+ params: object = call.params
211
+ if not isinstance(params, dict):
212
+ raise MockgunError('mockgun cannot activity_stream parameter params')
213
+ return read_stream(server.store, cast('dict[str, object]', params), context=context)
214
+
215
+
216
+ @_register('create')
217
+ def _create(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
218
+ """Create a record and return requested or supplied fields plus its identity."""
219
+ params = cast('dict[str, object]', call.params)
220
+ entity_type = cast('str', params['type'])
221
+ _check_event_write(server, entity_type)
222
+ fields, _ = _fields(params)
223
+ return_fields = cast('list[str]', params['return_fields'])
224
+ result_fields = list(fields)
225
+ for name in return_fields:
226
+ if '.' in name:
227
+ raise MockgunError(f'mockgun create() cannot return linked field path {name}')
228
+ if server.schema.declares(entity_type, name) and name not in result_fields:
229
+ result_fields.append(name)
230
+
231
+ candidate = server.store.prepare_create(entity_type, fields, context=context)
232
+ project_rows(server.store.preview(candidate), server.schema, [candidate], result_fields)
233
+ with server.store.transaction():
234
+ row = server.store.create(entity_type, fields, context=context)
235
+ result = project_rows(server.store, server.schema, [row], result_fields)[0]
236
+ settled = record_create(server.store, row, list(fields), context=context)
237
+ follow_created_note(server.store, row, context=context)
238
+ record_create_activity(server.store, row, settled=settled, context=context)
239
+ return result
240
+
241
+
242
+ @_register('delete')
243
+ def _delete(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
244
+ """Retire one existing record."""
245
+ params = cast('dict[str, object]', call.params)
246
+ entity_type = cast('str', params['type'])
247
+ _check_event_write(server, entity_type)
248
+ with server.store.transaction():
249
+ effects = retire(server.store, entity_type, cast('int', params['id']), context=context)
250
+ record_lifecycle(server.store, effects, revival=False, context=context)
251
+ record_lifecycle_activity(server.store, effects, context=context)
252
+ return effects.changed
253
+
254
+
255
+ @_register('follow')
256
+ def _follow(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
257
+ """Follow an active entity for an active HumanUser."""
258
+ del context
259
+ return follow(server.store, _follow_params('follow', call.params, ('user', 'entity')))
260
+
261
+
262
+ @_register('followers')
263
+ def _followers(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
264
+ """Read the observed follower shape for one active entity."""
265
+ del context
266
+ return followers(server.store, _follow_params('followers', call.params, ('entity',)))
267
+
268
+
269
+ @_register('following')
270
+ def _following(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
271
+ """Read a HumanUser's followed entities with optional filters."""
272
+ del context
273
+ return following(
274
+ server.store,
275
+ _follow_params('following', call.params, ('user',), ('project', 'entity_type')),
276
+ )
277
+
278
+
279
+ @_register('get_session_token', wrapped=False)
280
+ def _get_session_token(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
281
+ """Issue an unwrapped token response retaining the current credentials' actor."""
282
+ del call
283
+ actor = context.actor
284
+ if actor is None:
285
+ raise ServerFaultError('Authentication failed.', error_code=102)
286
+ return {
287
+ 'session_id': server.sessions.issue_token(actor),
288
+ 'user_type': actor.entity_type,
289
+ 'user_id': actor.entity_id,
290
+ }
291
+
292
+
293
+ @_register('note_thread_contents', wrapped=False)
294
+ def _note_thread_contents(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
295
+ """Return an unwrapped Note thread for validated wire parameters."""
296
+ params: object = call.params
297
+ if not isinstance(params, dict):
298
+ raise MockgunError('mockgun cannot note_thread_contents parameter params')
299
+ return read_thread(server.store, cast('dict[str, object]', params), context=context)
300
+
301
+
302
+ @_register('read')
303
+ def _read(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
304
+ """Select, page, and project a query using the site's current maximum width."""
305
+ params = cast('dict[str, object]', call.params)
306
+ entity_type = cast('str', params['type'])
307
+ return_fields = cast('list[str]', params['return_fields'])
308
+ if server.schema.declares(entity_type):
309
+ _check_connection_read(
310
+ entity_type,
311
+ return_fields,
312
+ cast('dict[str, object]', params['filters']),
313
+ cast('list[dict[str, str]]', params.get('sorts', [])),
314
+ )
315
+ presets = params.get('additional_filter_presets', [])
316
+ # ReadScope's None means omitted; preserve explicit wire null as a non-list.
317
+ if presets is None:
318
+ presets = ()
319
+ rows = select(
320
+ server.store,
321
+ entity_type,
322
+ cast('dict[str, object]', params['filters']),
323
+ cast('list[dict[str, str]]', params.get('sorts', [])),
324
+ scope=ReadScope(
325
+ retired=params.get('return_only') == 'retired',
326
+ context=context,
327
+ include_archived_projects=params.get('include_archived_projects') is not False,
328
+ presets=presets,
329
+ ),
330
+ )
331
+ paging = cast('dict[str, int]', params['paging'])
332
+ selected, paging_info = page(
333
+ rows,
334
+ entities_per_page=paging['entities_per_page'],
335
+ current_page=paging['current_page'],
336
+ max_page_size=cast('int', server.server_metadata()['api_max_entities_per_page']),
337
+ )
338
+ return {
339
+ 'entities': project_rows(
340
+ server.store, server.schema, selected, return_fields, context=context
341
+ ),
342
+ 'paging_info': paging_info,
343
+ }
344
+
345
+
346
+ @_register('query_display_name_cache', wrapped=False)
347
+ def _search(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
348
+ """Return matches and terms for a supported text search."""
349
+ params: object = call.params
350
+ if not isinstance(params, dict):
351
+ raise MockgunError('mockgun cannot query_display_name_cache this request yet')
352
+ return search(server.store, server.schema, cast('dict[str, object]', params), context=context)
353
+
354
+
355
+ @_register('summarize')
356
+ def _summarize(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
357
+ """Return totals and groups for a supported summary request."""
358
+ params: object = call.params
359
+ if not isinstance(params, dict):
360
+ raise MockgunError('mockgun cannot summarize this request yet')
361
+ return summarize(
362
+ server.store, server.schema, cast('dict[str, object]', params), context=context
363
+ )
364
+
365
+
366
+ @_register('revive')
367
+ def _revive(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
368
+ """Restore one existing retired record."""
369
+ params = cast('dict[str, object]', call.params)
370
+ entity_type = cast('str', params['type'])
371
+ _check_event_write(server, entity_type)
372
+ with server.store.transaction():
373
+ effects = revive(server.store, entity_type, cast('int', params['id']), context=context)
374
+ record_lifecycle(server.store, effects, revival=True, context=context)
375
+ record_lifecycle_activity(server.store, effects, context=context)
376
+ return effects.changed
377
+
378
+
379
+ @_register('update')
380
+ def _update(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
381
+ """Update a record and return the submitted fields plus its identity."""
382
+ params = cast('dict[str, object]', call.params)
383
+ fields, modes = _fields(params)
384
+
385
+ entity_type = cast('str', params['type'])
386
+ entity_id = cast('int', params['id'])
387
+ _check_event_write(server, entity_type)
388
+ kept = kept_members(server.store, entity_type, entity_id, fields)
389
+ effective = server.store.kept_fields(
390
+ server.store.require(entity_type, entity_id), fields, modes, kept
391
+ )
392
+ effective_modes = {**modes, **dict.fromkeys(kept, 'set')}
393
+ candidate = server.store.prepare_update(
394
+ entity_type, entity_id, effective, effective_modes, context=context
395
+ )
396
+ result = project_rows(
397
+ server.store.preview(candidate), server.schema, [candidate], list(fields)
398
+ )[0]
399
+ with server.store.transaction():
400
+ before = deepcopy(server.store.require(entity_type, entity_id))
401
+ row = server.store.update(
402
+ entity_type, entity_id, effective, effective_modes, context=context
403
+ )
404
+ for field in kept:
405
+ if len(cast('list[FieldValue]', row[field])) > 1:
406
+ server.store.mark_unknown(
407
+ row, field, 'retained hidden members have unsettled order', order_only=True
408
+ )
409
+ settled = record_update(
410
+ server.store,
411
+ before,
412
+ row,
413
+ {field: modes.get(field, 'set') for field in fields},
414
+ context=context,
415
+ )
416
+ record_update_activity(server.store, before, row, settled=settled, context=context)
417
+ if {'image', 'filmstrip_image'} & fields.keys():
418
+ taint_activity(
419
+ server.store,
420
+ [before, row],
421
+ f'update {entity_type} {entity_id} image fields: activity is unsettled',
422
+ )
423
+ return result
424
+
425
+
426
+ @_register('unfollow')
427
+ def _unfollow(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
428
+ """Remove a HumanUser follow of an active entity."""
429
+ del context
430
+ return unfollow(server.store, _follow_params('unfollow', call.params, ('user', 'entity')))
431
+
432
+
433
+ @_register('batch')
434
+ def _batch(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
435
+ """Apply writes in order, restoring all tables if any request fails."""
436
+ results: list[object] = []
437
+ with server.store.transaction():
438
+ for params in cast('list[dict[str, object]]', call.params):
439
+ method = cast('str', params['request_type'])
440
+ results.append(HANDLERS[method](server, RpcCall(method, call.auth, params), context))
441
+ return results
442
+
443
+
444
+ @_register('info', wrapped=False)
445
+ def _info(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
446
+ """Return the site's current readiness metadata."""
447
+ del call, context
448
+ return server.server_metadata()
449
+
450
+
451
+ @_register('schema_entity_read')
452
+ def _schema_entity_read(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
453
+ """Return entity metadata without Project-specific visibility changes."""
454
+ del context
455
+ project_id = _schema_project_id(call.params)
456
+ if project_id is not None:
457
+ raise MockgunError(
458
+ f'schema_entity_read Project {project_id} project-specific entity schema is unsettled'
459
+ )
460
+ return server.schema.entities
461
+
462
+
463
+ @_register('schema_field_create')
464
+ def _schema_field_create(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
465
+ """Create a field in the site's mutable schema and existing records."""
466
+ params = cast('dict[str, object]', call.params)
467
+ entity_type = cast('str', params['type'])
468
+ data_type = cast('str', params['data_type'])
469
+ properties = cast('list[dict[str, object]]', params['properties'])
470
+ field_name, _ = create_field(server.schema, entity_type, data_type, properties)
471
+ server.store.add_field(entity_type, field_name)
472
+ record_schema_write(server.store, 'create', data_type, properties, context=context)
473
+ return field_name
474
+
475
+
476
+ @_register('schema_field_delete')
477
+ def _schema_field_delete(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
478
+ """Delete one custom field and reserve its internal name."""
479
+ params = cast('dict[str, object]', call.params)
480
+ entity_type = cast('str', params['type'])
481
+ field_name = cast('str', params['field_name'])
482
+ field = server.schema.fields.get(entity_type, {}).get(field_name)
483
+ data_type = ''
484
+ if isinstance(field, dict):
485
+ metadata = cast('dict[str, object]', field)
486
+ data_type = cast('str', cast('dict[str, object]', metadata['data_type'])['value'])
487
+ delete_field(server.schema, entity_type, field_name)
488
+ server.store.drop_field(entity_type, field_name)
489
+ record_schema_write(server.store, 'delete', data_type, [], context=context)
490
+ return True
491
+
492
+
493
+ @_register('schema_field_read')
494
+ def _schema_field_read(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
495
+ """Select field metadata for an entity and optional field name."""
496
+ del context
497
+ params = cast('dict[str, object]', call.params)
498
+ entity_type = cast('str', params['type'])
499
+ if not server.schema.declares(entity_type):
500
+ raise ServerFaultError(f'{entity_type} is not a valid entity')
501
+ fields = server.schema.scoped(_schema_project_id(params), entity_type)[entity_type]
502
+ field_name = params.get('field_name')
503
+ if field_name is None:
504
+ return fields
505
+ if field_name not in fields:
506
+ raise ServerFaultError(
507
+ f"API schema_field_read() {entity_type}.{field_name} doesn't exist:\n"
508
+ f'{{"type" => "{entity_type}", "field_name" => "{field_name}"}}',
509
+ error_code=103,
510
+ )
511
+ return {cast('str', field_name): fields[cast('str', field_name)]}
512
+
513
+
514
+ @_register('schema_field_update')
515
+ def _schema_field_update(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
516
+ """Validate Project scope and update one custom field's metadata."""
517
+ params = cast('dict[str, object]', call.params)
518
+ entity_type = cast('str', params['type'])
519
+ field_name = cast('str', params['field_name'])
520
+ project = params.get('project')
521
+ project_id: int | None = None
522
+ if project is not None:
523
+ if not isinstance(project, dict):
524
+ raise MockgunError(
525
+ f'schema_field_update {entity_type}.{field_name}: project link is unsettled'
526
+ )
527
+ project_link = cast('dict[str, object]', project)
528
+ if project_link.get('type') != 'Project':
529
+ raise MockgunError(
530
+ f'schema_field_update {entity_type}.{field_name}: project link is unsettled'
531
+ )
532
+ identity = project_link.get('id')
533
+ if (
534
+ not isinstance(identity, int)
535
+ or isinstance(identity, bool)
536
+ or not server.schema.declares('Project')
537
+ or server.store.row('Project', identity) is None
538
+ ):
539
+ raise MockgunError(
540
+ f'schema_field_update {entity_type}.{field_name}: project link is unsettled'
541
+ )
542
+ project_id = identity
543
+ properties = cast('list[dict[str, object]]', params['properties'])
544
+ field = server.schema.fields.get(entity_type, {}).get(field_name)
545
+ data_type = ''
546
+ if isinstance(field, dict):
547
+ metadata = cast('dict[str, object]', field)
548
+ data_type = cast('str', cast('dict[str, object]', metadata['data_type'])['value'])
549
+ update_field(server.schema, entity_type, field_name, properties, project_id=project_id)
550
+ record_schema_write(server.store, 'update', data_type, properties, context=context)
551
+ return True
552
+
553
+
554
+ @_register('schema_read')
555
+ def _schema_read(server: 'FakeServer', call: RpcCall, context: RequestContext) -> object:
556
+ """Return the loaded field metadata without added declarations."""
557
+ del context
558
+ return server.schema.scoped(_schema_project_id(call.params))