codemie-cdk-python 0.1.0rc0__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 (39) hide show
  1. codemie_cdk_python-0.1.0rc0.dist-info/METADATA +840 -0
  2. codemie_cdk_python-0.1.0rc0.dist-info/RECORD +39 -0
  3. codemie_cdk_python-0.1.0rc0.dist-info/WHEEL +4 -0
  4. codemie_cdk_python-0.1.0rc0.dist-info/entry_points.txt +3 -0
  5. codemie_iac/__init__.py +49 -0
  6. codemie_iac/cli/__init__.py +17 -0
  7. codemie_iac/cli/__main__.py +24 -0
  8. codemie_iac/cli/commands/__init__.py +17 -0
  9. codemie_iac/cli/commands/apply.py +119 -0
  10. codemie_iac/cli/commands/plan.py +72 -0
  11. codemie_iac/cli/documents.py +59 -0
  12. codemie_iac/cli/env_file.py +62 -0
  13. codemie_iac/cli/exit_status.py +80 -0
  14. codemie_iac/cli/main.py +118 -0
  15. codemie_iac/cli/render.py +206 -0
  16. codemie_iac/cli/target_config.py +230 -0
  17. codemie_iac/cli/token_client.py +42 -0
  18. codemie_iac/credentials.py +99 -0
  19. codemie_iac/envelope.py +188 -0
  20. codemie_iac/plan_apply/__init__.py +70 -0
  21. codemie_iac/plan_apply/bulk_create.py +561 -0
  22. codemie_iac/plan_apply/credentials.py +306 -0
  23. codemie_iac/plan_apply/errors.py +223 -0
  24. codemie_iac/plan_apply/field_policy.py +185 -0
  25. codemie_iac/plan_apply/guards.py +221 -0
  26. codemie_iac/plan_apply/kinds.py +815 -0
  27. codemie_iac/plan_apply/lookup.py +313 -0
  28. codemie_iac/plan_apply/ordering.py +177 -0
  29. codemie_iac/plan_apply/single_apply.py +751 -0
  30. codemie_iac/resolver.py +61 -0
  31. codemie_iac/schema.py +106 -0
  32. codemie_iac/serializer.py +64 -0
  33. codemie_iac/specs/__init__.py +13 -0
  34. codemie_iac/specs/assistant.py +509 -0
  35. codemie_iac/specs/category.py +36 -0
  36. codemie_iac/specs/datasource.py +595 -0
  37. codemie_iac/specs/integration.py +103 -0
  38. codemie_iac/specs/skill.py +51 -0
  39. codemie_iac/specs/workflow.py +154 -0
@@ -0,0 +1,815 @@
1
+ # Copyright 2026 EPAM Systems, Inc. ("EPAM")
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Per-kind adapter tables binding IaC documents to ``codemie_sdk`` services.
16
+
17
+ Every operation of a ``KindAdapter`` takes the SDK client (anything exposing
18
+ the service attributes of ``CodeMieClient``: ``assistants``, ``skills``,
19
+ ``workflows``, ``datasources``, ``integrations``, ``categories``) and the
20
+ ``Document``, so callers never branch on the kind:
21
+
22
+ adapter = adapter_for(document)
23
+ response = adapter.create(client, document, resolved)
24
+ entity_id = adapter.extract_id(response)
25
+
26
+ ``resolved`` is a mapping of request-body field overrides produced by the
27
+ reference/credential resolution step (platform ids, credential values, a
28
+ workflow's ``project``...). It is merged over the body derived from the
29
+ document spec; two keys are special for workflows: ``yaml_config`` (a
30
+ pre-rendered config) and ``resolve_assistant_name`` (a callable passed to
31
+ ``WorkflowDefinition.to_yaml_config``). Platform ids are only passed in and
32
+ returned, never stored.
33
+ """
34
+
35
+ import logging
36
+ from collections.abc import Callable, Iterator, Mapping
37
+ from contextlib import contextmanager
38
+ from dataclasses import dataclass
39
+ from typing import Any
40
+
41
+ from codemie_sdk.exceptions import NotFoundError
42
+ from codemie_sdk.models.assistant import AssistantCreateRequest, AssistantUpdateRequest
43
+ from codemie_sdk.models.categories import CategoryCreateRequest, CategoryUpdateRequest
44
+ from codemie_sdk.models.datasource import (
45
+ AzureDevOpsWikiDataSourceRequest,
46
+ AzureDevOpsWorkItemDataSourceRequest,
47
+ CodeDataSourceRequest,
48
+ ConfluenceDataSourceRequest,
49
+ GitFaqDataSourceRequest,
50
+ GoogleDataSourceRequest,
51
+ JiraDataSourceRequest,
52
+ ProviderDataSourceRequest,
53
+ SharePointDataSourceRequest,
54
+ SvnDataSourceRequest,
55
+ UpdateAzureDevOpsWikiDataSourceRequest,
56
+ UpdateAzureDevOpsWorkItemDataSourceRequest,
57
+ UpdateCodeDataSourceRequest,
58
+ UpdateConfluenceDataSourceRequest,
59
+ UpdateGitFaqDataSourceRequest,
60
+ UpdateGoogleDataSourceRequest,
61
+ UpdateJiraDataSourceRequest,
62
+ UpdateProviderDataSourceRequest,
63
+ UpdateSharePointDataSourceRequest,
64
+ UpdateSvnDataSourceRequest,
65
+ UpdateXrayDataSourceRequest,
66
+ UpdateXWikiDataSourceRequest,
67
+ XrayDataSourceRequest,
68
+ XWikiDataSourceRequest,
69
+ )
70
+ from codemie_sdk.models.integration import Integration
71
+ from codemie_sdk.models.skill import SkillCreateRequest, SkillUpdateRequest
72
+ from codemie_sdk.models.workflow import WorkflowCreateRequest, WorkflowUpdateRequest
73
+ from pydantic import BaseModel, ValidationError
74
+
75
+ from ..envelope import Document, DocumentKind
76
+ from .errors import ApplyError
77
+
78
+ logger = logging.getLogger(__name__)
79
+
80
+ __all__ = [
81
+ "ADAPTERS",
82
+ "DATASOURCE_ADAPTERS",
83
+ "INTEGRATION_LIST_CAP",
84
+ "KindAdapter",
85
+ "adapter_for",
86
+ ]
87
+
88
+ #: ``IntegrationService.get`` looks an integration up by listing, 100 items max.
89
+ INTEGRATION_LIST_CAP = 100
90
+
91
+ Resolved = Mapping[str, Any]
92
+ _ID_KEYS = ("assistant_id", "id", "workflow_id", "setting_id")
93
+
94
+
95
+ @dataclass(frozen=True)
96
+ class KindAdapter:
97
+ """Operations for one kind (or one datasource type).
98
+
99
+ create(client, document, resolved) -> raw SDK response
100
+ update(client, document, entity_id, resolved, changed=None) -> raw SDK
101
+ response; ``changed`` names the fields a plan found different (or
102
+ could not compare), ``None`` meaning "unknown: write everything"
103
+ get(client, document, entity_id) -> live SDK object
104
+ extract_id(response) -> platform id, or None when the response has none
105
+ to_comparable(live) -> plain dict of the live object's fields
106
+ find_id(client, document) -> id of the created entity looked up by its
107
+ identity, for kinds whose create response carries no id
108
+ """
109
+
110
+ create: Callable[[Any, Document, Resolved], Any]
111
+ update: Callable[..., Any]
112
+ get: Callable[[Any, Document, str], Any]
113
+ extract_id: Callable[[Any], str | None]
114
+ to_comparable: Callable[[Any], dict[str, Any]]
115
+ find_id: Callable[[Any, Document], str | None] | None = None
116
+
117
+
118
+ def created_id(
119
+ adapter: KindAdapter, client: Any, document: Document, response: Any
120
+ ) -> str | None:
121
+ """The id of a just-created entity: from the response, else by lookup.
122
+
123
+ The entity already exists when the lookup runs, so a lookup failure is
124
+ logged and answered with ``None`` rather than failing the create."""
125
+ entity_id = adapter.extract_id(response)
126
+ if entity_id is None and adapter.find_id is not None:
127
+ try:
128
+ entity_id = adapter.find_id(client, document)
129
+ except Exception as exc: # noqa: BLE001 - the entity exists; never fail the create
130
+ logger.warning(
131
+ "created %s %r in project %r but could not look its id up: %s",
132
+ document.meta.kind.value,
133
+ document.meta.name,
134
+ getattr(document.spec, "project_name", None),
135
+ type(exc).__name__,
136
+ )
137
+ return entity_id
138
+
139
+
140
+ # --- shared helpers --------------------------------------------------------
141
+
142
+
143
+ def _extract_id(response: Any) -> str | None:
144
+ for key in _ID_KEYS:
145
+ value = (
146
+ response.get(key)
147
+ if isinstance(response, dict)
148
+ else getattr(response, key, None)
149
+ )
150
+ if isinstance(value, str) and value:
151
+ return value
152
+ return None
153
+
154
+
155
+ def _no_id(_response: Any) -> None:
156
+ return None
157
+
158
+
159
+ def _to_comparable(live: Any) -> dict[str, Any]:
160
+ if isinstance(live, BaseModel):
161
+ return live.model_dump(mode="json")
162
+ if isinstance(live, dict):
163
+ return dict(live)
164
+ return dict(vars(live))
165
+
166
+
167
+ def _build(request_cls: type[BaseModel], data: dict, document: Document) -> Any:
168
+ try:
169
+ return request_cls(**data)
170
+ except ValidationError as exc:
171
+ # Raised below, outside the handler, so that neither the cause nor the
172
+ # context (the offending input) stays reachable from the error.
173
+ # Never ``str(exc)``: pydantic embeds the offending input, which here
174
+ # may be a revealed credential.
175
+ reason = "; ".join(
176
+ f"{'.'.join(str(p) for p in e['loc']) or '<body>'}: {e['msg']}"
177
+ for e in exc.errors(
178
+ include_input=False, include_url=False, include_context=False
179
+ )
180
+ )
181
+ error = ApplyError(
182
+ "invalid_body", document.meta.kind.value, document.meta.name, reason
183
+ )
184
+ raise error
185
+
186
+
187
+ def _spec_body(document: Document, resolved: Resolved, **exclude: Any) -> dict:
188
+ body = document.spec.model_dump(mode="python", exclude=set(exclude) or None)
189
+ body.update(resolved)
190
+ return body
191
+
192
+
193
+ def _clear_omitted_icon(body: dict, live: Any) -> dict:
194
+ """An omitted ``icon_url`` clears one that is set on the live entity.
195
+
196
+ Neither the SDK (``exclude_none``) nor the backend (``if value is not None``)
197
+ treats ``None`` as "clear", so an empty string is sent instead.
198
+ """
199
+ if body.get("icon_url") is None and getattr(live, "icon_url", None):
200
+ body["icon_url"] = ""
201
+ return body
202
+
203
+
204
+ def _assistant_update_body(document: Document, resolved: Resolved, live: Any) -> dict:
205
+ return _clear_omitted_icon(_spec_body(document, resolved), live)
206
+
207
+
208
+ def _workflow_body(document: Document, resolved: Resolved) -> dict:
209
+ definition = document.spec.workflow
210
+ overrides = dict(resolved)
211
+ resolver = overrides.pop("resolve_assistant_name", None)
212
+ yaml_config = overrides.pop("yaml_config", None)
213
+ if yaml_config is None:
214
+ yaml_config = definition.to_yaml_config(resolver)
215
+ body = {
216
+ "name": definition.name,
217
+ "description": definition.description,
218
+ "mode": definition.mode,
219
+ "shared": definition.shared,
220
+ "icon_url": definition.icon_url,
221
+ "yaml_config": yaml_config,
222
+ "start_hint": document.spec.start_hint,
223
+ }
224
+ body.update(overrides)
225
+ return body
226
+
227
+
228
+ def _workflow_update_body(document: Document, resolved: Resolved, live: Any) -> dict:
229
+ return _clear_omitted_icon(_workflow_body(document, resolved), live)
230
+
231
+
232
+ def _integration_body(document: Document, resolved: Resolved) -> dict:
233
+ # Credential values only ever come from ``resolved``; the spec holds refs.
234
+ return _spec_body(document, resolved, credential_values=None)
235
+
236
+
237
+ def _datasource_body(document: Document, resolved: Resolved) -> dict:
238
+ body = _spec_body(document, resolved)
239
+ body.pop("type", None) # the request classes fix their own type
240
+ # The requests name the flag by its camelCase alias; the typed svn,
241
+ # SharePoint and Xray requests refuse the field name beside it.
242
+ visible = body.pop("shared_with_project", False)
243
+ body.setdefault("project_space_visible", visible)
244
+ # An omitted svn branch is the SDK's default on create and the stored value
245
+ # on update; the request rejects an explicit None.
246
+ if document.spec.type == "svn" and body.get("branch") is None:
247
+ body.pop("branch", None)
248
+ return body
249
+
250
+
251
+ #: Fields the backend PUT overwrites when omitted, per datasource type: an
252
+ #: update must always send them, from the document or else from live state.
253
+ _HAZARD_FIELDS: dict[str, tuple[str, ...]] = {
254
+ "svn": ("prompt", "files_filter", "project_space_visible", "docs_generation"),
255
+ # ``auth_type`` is filled from live state so the SDK can see a stored OAuth
256
+ # type and ask for the token before a reindex is sent.
257
+ "knowledge_base_sharepoint": ("files_filter", "auth_type"),
258
+ "provider": ("description", "project_space_visible"),
259
+ }
260
+
261
+ #: Hazard fields the update request requires: a missing value cannot be sent.
262
+ _REQUIRED_HAZARD_FIELDS: dict[str, tuple[str, ...]] = {
263
+ "provider": ("description", "project_space_visible"),
264
+ }
265
+
266
+ #: Document fields an update request cannot carry, per datasource type.
267
+ _CREATE_ONLY_FIELDS: dict[str, tuple[str, ...]] = {
268
+ "svn": ("index_type",),
269
+ # The Xray update route does not pass the embedding model to the index.
270
+ "knowledge_base_xray": ("embedding_model",),
271
+ }
272
+
273
+ #: Request field -> the differently named field on the spec and on the live
274
+ #: ``DataSource`` top level. Other hazard fields live in the type's sub-object.
275
+ _TOP_LEVEL_FIELDS = {
276
+ "project_space_visible": "shared_with_project",
277
+ "description": "description",
278
+ }
279
+ _LIVE_SUBOBJECT = {"svn": "svn", "knowledge_base_sharepoint": "sharepoint"}
280
+
281
+
282
+ def _is_authored(document: Document, resolved: Resolved, field: str) -> bool:
283
+ spec_field = _TOP_LEVEL_FIELDS.get(field, field)
284
+ spec = document.spec
285
+ return field in resolved or (
286
+ spec_field in spec.model_fields_set and getattr(spec, spec_field) is not None
287
+ )
288
+
289
+
290
+ def _live_value(live: Mapping[str, Any], ds_type: str, field: str) -> Any:
291
+ top_field = _TOP_LEVEL_FIELDS.get(field)
292
+ if top_field:
293
+ return live.get(top_field)
294
+ return (live.get(_LIVE_SUBOBJECT.get(ds_type, "")) or {}).get(field)
295
+
296
+
297
+ def _complete_body(document: Document, resolved: Resolved, live: Any) -> dict:
298
+ """The datasource body with every hazard field filled: from the document
299
+ when it authors the field, else from the live value."""
300
+ body = _datasource_body(document, resolved)
301
+ ds_type = document.spec.type
302
+ live = _to_comparable(live) if not isinstance(live, Mapping) else live
303
+ for field in _CREATE_ONLY_FIELDS.get(ds_type, ()):
304
+ body.pop(field, None)
305
+ for field in _HAZARD_FIELDS.get(ds_type, ()):
306
+ if _is_authored(document, resolved, field):
307
+ continue
308
+ live_value = _live_value(live, ds_type, field)
309
+ if live_value is not None:
310
+ body[field] = live_value
311
+ elif field in _REQUIRED_HAZARD_FIELDS.get(ds_type, ()):
312
+ raise ApplyError(
313
+ "missing_required_field",
314
+ "datasource",
315
+ document.meta.name,
316
+ f"{field!r} is required on update but is neither set in the "
317
+ "document nor present on the live datasource; set it in the document",
318
+ )
319
+ return body
320
+
321
+
322
+ @contextmanager
323
+ def _no_request_body_log() -> Iterator[None]:
324
+ """Keep the SDK from logging request bodies while a write is sent.
325
+
326
+ The SDK logs ``Request body: ...`` at DEBUG for every POST and PUT, and
327
+ the bodies carry the resolved credentials, which no scrubbing can reach.
328
+ """
329
+ logger = logging.getLogger("codemie_sdk.utils.http")
330
+ level = logger.level
331
+ logger.setLevel(max(level, logging.INFO))
332
+ try:
333
+ yield
334
+ finally:
335
+ logger.setLevel(level)
336
+
337
+
338
+ def _reject_declined_assistant(response: Any, document: Document) -> None:
339
+ """The platform answers HTTP 200 with the validation result and saves
340
+ nothing when a tool has no usable integration."""
341
+ validation = getattr(response, "validation", None)
342
+ if validation is None or not getattr(validation, "has_missing_integrations", True):
343
+ return
344
+ types = sorted(
345
+ {
346
+ str(getattr(m, "credential_type", ""))
347
+ for m in getattr(validation, "missing_by_credential_type", None) or []
348
+ }
349
+ - {""}
350
+ )
351
+ raise ApplyError(
352
+ "integration_missing",
353
+ document.meta.kind.value,
354
+ document.meta.name,
355
+ "the platform did not save the assistant: some tools have no "
356
+ "integration it can use"
357
+ + (f" (credential types: {', '.join(types)})" if types else "")
358
+ + "; pin an integration on them or create it first",
359
+ )
360
+
361
+
362
+ def _make_adapter(
363
+ *,
364
+ service: str,
365
+ body: Callable[[Document, Resolved], dict],
366
+ create_cls: type[BaseModel],
367
+ update_cls: type[BaseModel],
368
+ create_method: str = "create",
369
+ update_method: str = "update",
370
+ get_method: str = "get",
371
+ extract: Callable[[Any], str | None] = _extract_id,
372
+ get_fn: Callable[[Any, Document, str], Any] | None = None,
373
+ update_body: Callable[[Document, Resolved, Any], dict] | None = None,
374
+ to_comparable: Callable[[Any], dict[str, Any]] = _to_comparable,
375
+ find_id: Callable[[Any, Document], str | None] | None = None,
376
+ adjust_update: Callable[[dict, frozenset[str] | None], dict] | None = None,
377
+ check_response: Callable[[Any, Document], None] | None = None,
378
+ ) -> KindAdapter:
379
+ def send(method, document, *args):
380
+ with _no_request_body_log():
381
+ response = method(*args)
382
+ if check_response is not None:
383
+ check_response(response, document)
384
+ return response
385
+
386
+ def create(client, document, resolved):
387
+ request = _build(create_cls, body(document, resolved), document)
388
+ method = getattr(getattr(client, service), create_method)
389
+ return send(method, document, request)
390
+
391
+ def get(client, document, entity_id):
392
+ return getattr(getattr(client, service), get_method)(entity_id)
393
+
394
+ def update(client, document, entity_id, resolved, changed=None):
395
+ if update_body is None:
396
+ data = body(document, resolved)
397
+ else:
398
+ live = (get_fn or get)(client, document, entity_id)
399
+ data = update_body(document, resolved, live)
400
+ if adjust_update is not None:
401
+ data = adjust_update(data, changed)
402
+ request = _build(update_cls, data, document)
403
+ method = getattr(getattr(client, service), update_method)
404
+ return send(method, document, entity_id, request)
405
+
406
+ return KindAdapter(
407
+ create=create,
408
+ update=update,
409
+ get=get_fn or get,
410
+ extract_id=extract,
411
+ to_comparable=to_comparable,
412
+ find_id=find_id,
413
+ )
414
+
415
+
416
+ def _get_integration(client: Any, document: Document, entity_id: str) -> Any:
417
+ try:
418
+ return client.integrations.get(
419
+ entity_id, setting_type=document.spec.setting_type
420
+ )
421
+ except NotFoundError as exc:
422
+ raise ApplyError(
423
+ "integration_not_found",
424
+ document.meta.kind.value,
425
+ document.meta.name,
426
+ f"integration {entity_id!r} not found; lookup lists at most "
427
+ f"{INTEGRATION_LIST_CAP} integrations, so it may exist beyond the "
428
+ f"{INTEGRATION_LIST_CAP}-item cap",
429
+ ) from exc
430
+
431
+
432
+ # --- datasource sub-table, keyed by spec ``type`` ----------------------------
433
+
434
+ # ``knowledge_base_file`` is deliberately absent: file datasources are rejected
435
+ # by ``guards.guard_supported``, before an adapter is ever requested.
436
+ _DATASOURCE_CLASSES: dict[str, tuple[type[BaseModel], type[BaseModel]]] = {
437
+ "code": (CodeDataSourceRequest, UpdateCodeDataSourceRequest),
438
+ "knowledge_base_git_faq": (GitFaqDataSourceRequest, UpdateGitFaqDataSourceRequest),
439
+ "knowledge_base_jira": (JiraDataSourceRequest, UpdateJiraDataSourceRequest),
440
+ "knowledge_base_confluence": (
441
+ ConfluenceDataSourceRequest,
442
+ UpdateConfluenceDataSourceRequest,
443
+ ),
444
+ "llm_routing_google": (GoogleDataSourceRequest, UpdateGoogleDataSourceRequest),
445
+ "knowledge_base_azure_devops_wiki": (
446
+ AzureDevOpsWikiDataSourceRequest,
447
+ UpdateAzureDevOpsWikiDataSourceRequest,
448
+ ),
449
+ "knowledge_base_azure_devops_work_item": (
450
+ AzureDevOpsWorkItemDataSourceRequest,
451
+ UpdateAzureDevOpsWorkItemDataSourceRequest,
452
+ ),
453
+ "knowledge_base_xwiki": (XWikiDataSourceRequest, UpdateXWikiDataSourceRequest),
454
+ "svn": (SvnDataSourceRequest, UpdateSvnDataSourceRequest),
455
+ "knowledge_base_sharepoint": (
456
+ SharePointDataSourceRequest,
457
+ UpdateSharePointDataSourceRequest,
458
+ ),
459
+ "knowledge_base_xray": (XrayDataSourceRequest, UpdateXrayDataSourceRequest),
460
+ }
461
+
462
+ # --- datasource live view ------------------------------------------------------
463
+ #
464
+ # The live view is the SDK ``DataSource`` model as read, with two adjustments
465
+ # for how a document describes a datasource.
466
+
467
+ # A document's code datasource is always ``type: code``; the SDK reports the
468
+ # index type (``code``, ``summary`` or ``chunk-summary``) as the datasource
469
+ # type. The index type itself is compared through the code sub-object. An SVN
470
+ # datasource is reported under the same index types.
471
+ _CODE_FAMILY = frozenset({"code", "summary", "chunk-summary"})
472
+
473
+
474
+ def _datasource_view(live: Any) -> dict[str, Any]:
475
+ view = _to_comparable(live)
476
+ if view.get("type") in _CODE_FAMILY:
477
+ # An SVN datasource is stored under a code index type; its settings
478
+ # come from the ``svn`` sub-object, not the code one.
479
+ if view.get("svn") is not None:
480
+ view["type"] = "svn"
481
+ view.pop("code", None)
482
+ else:
483
+ view["type"] = "code"
484
+ # Without a schedule the backend reports its default timezone, which a
485
+ # document does not author: only expose the timezone alongside a cron.
486
+ if not view.get("cron_expression"):
487
+ view.pop("timezone", None)
488
+ return view
489
+
490
+
491
+ def _datasource_get(client: Any, document: Document, entity_id: str) -> Any:
492
+ return _datasource_view(client.datasources.get(entity_id))
493
+
494
+
495
+ #: A datasource create answers a message only, so the new id is looked up by
496
+ #: project and name. Listing has no name filter: it pages through the project.
497
+ _FIND_PAGE_SIZE = 100
498
+ _FIND_MAX_PAGES = 20
499
+
500
+
501
+ def _find_datasource_id(client: Any, document: Document) -> str | None:
502
+ spec = document.spec
503
+ for page in range(_FIND_MAX_PAGES):
504
+ found = client.datasources.list(
505
+ page=page, per_page=_FIND_PAGE_SIZE, projects=[spec.project_name]
506
+ )
507
+ for item in found:
508
+ # Name and project are unique across all datasource types; the list
509
+ # item does not say whether it is an svn one, so the type is not
510
+ # compared.
511
+ if item.name == spec.name and item.project_name == spec.project_name:
512
+ return item.id
513
+ if len(found) < _FIND_PAGE_SIZE:
514
+ return None
515
+ logger.warning(
516
+ "datasource %r in project %r not found within %d list pages",
517
+ spec.name,
518
+ spec.project_name,
519
+ _FIND_MAX_PAGES,
520
+ )
521
+ return None
522
+
523
+
524
+ # --- reindex-aware updates -------------------------------------------------------
525
+ #
526
+ # What a datasource update reindexes depends on the route. Code routes start an
527
+ # incremental reindex unless ``skip_reindex`` is set. The knowledge-base routes
528
+ # store a changed source and reindex only when ``full_reindex`` is set, so a
529
+ # source change without it leaves the index on the old source. ``changed``
530
+ # (see ``KindAdapter``) names the fields the plan found different (or could
531
+ # not compare); it never grows a reindex out of an unrelated write, such as a
532
+ # forced one that only pushes a rotated secret.
533
+
534
+ #: Per datasource type, the fields whose change needs a full reindex.
535
+ _REINDEX_SOURCE_FIELDS = {
536
+ "knowledge_base_git_faq": frozenset(
537
+ {"link", "branch", "files_filter", "setting_id"}
538
+ ),
539
+ "knowledge_base_jira": frozenset({"jql", "custom_fields", "setting_id"}),
540
+ "knowledge_base_confluence": frozenset({"cql", "setting_id"}),
541
+ "knowledge_base_azure_devops_wiki": frozenset({"wiki_query", "setting_id"}),
542
+ "knowledge_base_azure_devops_work_item": frozenset({"wiql_query", "setting_id"}),
543
+ "knowledge_base_xwiki": frozenset({"space", "wiki", "setting_id"}),
544
+ "knowledge_base_sharepoint": frozenset(
545
+ {
546
+ "site_url",
547
+ "include_pages",
548
+ "include_documents",
549
+ "include_lists",
550
+ "max_file_size_mb",
551
+ "files_filter",
552
+ "auth_type",
553
+ "oauth_client_id",
554
+ "oauth_tenant_id",
555
+ "embedding_model",
556
+ "setting_id",
557
+ }
558
+ ),
559
+ "knowledge_base_xray": frozenset({"jql", "setting_id"}),
560
+ }
561
+ #: Types whose route answers 422 to a source field sent without a full reindex.
562
+ _OMIT_UNCHANGED_SOURCE = frozenset({"knowledge_base_git_faq"})
563
+ #: Code datasource fields whose change needs no reindex.
564
+ _CODE_METADATA_FIELDS = frozenset(
565
+ {
566
+ "description",
567
+ "shared_with_project",
568
+ "project_space_visible",
569
+ "cron_expression",
570
+ "timezone",
571
+ }
572
+ )
573
+
574
+
575
+ def _source_update(ds_type: str) -> Callable[[dict, frozenset[str] | None], dict]:
576
+ source = _REINDEX_SOURCE_FIELDS[ds_type]
577
+
578
+ def adjust(data: dict, changed: frozenset[str] | None) -> dict:
579
+ if changed is None or changed & source:
580
+ return {**data, "full_reindex": True}
581
+ if ds_type in _OMIT_UNCHANGED_SOURCE:
582
+ return {k: v for k, v in data.items() if k not in source}
583
+ return data
584
+
585
+ return adjust
586
+
587
+
588
+ def _code_update(data: dict, changed: frozenset[str] | None) -> dict:
589
+ """Metadata-only changes skip the reindex. The update route reads the
590
+ visibility only from the camelCase key, which the SDK's update request does
591
+ not model, so it is added as an extra field."""
592
+ data = {**data, "projectSpaceVisible": data.get("project_space_visible")}
593
+ if changed is not None and changed <= _CODE_METADATA_FIELDS:
594
+ data["skip_reindex"] = True
595
+ return data
596
+
597
+
598
+ def _svn_update(data: dict, changed: frozenset[str] | None) -> dict:
599
+ """Like code: the backend reprocesses the repository on every update unless
600
+ ``skip_reindex`` is set, so a metadata-only change skips it."""
601
+ if changed is not None and changed <= _CODE_METADATA_FIELDS:
602
+ return {**data, "skip_reindex": True}
603
+ return data
604
+
605
+
606
+ _UPDATE_ADJUSTERS = {
607
+ "code": _code_update,
608
+ "svn": _svn_update,
609
+ **{ds_type: _source_update(ds_type) for ds_type in _REINDEX_SOURCE_FIELDS},
610
+ }
611
+
612
+ DATASOURCE_ADAPTERS: dict[str, KindAdapter] = {
613
+ ds_type: _make_adapter(
614
+ service="datasources",
615
+ body=_datasource_body,
616
+ create_cls=create_cls,
617
+ update_cls=update_cls,
618
+ extract=_no_id,
619
+ get_fn=_datasource_get,
620
+ update_body=(
621
+ _complete_body
622
+ if ds_type in _HAZARD_FIELDS or ds_type in _CREATE_ONLY_FIELDS
623
+ else None
624
+ ),
625
+ to_comparable=_datasource_view,
626
+ find_id=_find_datasource_id,
627
+ adjust_update=_UPDATE_ADJUSTERS.get(ds_type),
628
+ )
629
+ for ds_type, (create_cls, update_cls) in _DATASOURCE_CLASSES.items()
630
+ }
631
+
632
+
633
+ #: The provider update request has no ``name`` / ``project_name`` field, yet
634
+ #: the backend reads both from the PUT body and clears them when absent. Its
635
+ #: body merges ``settings``, so they travel there.
636
+ _PROVIDER_UPDATE_IDENTITY = ("name", "project_name")
637
+
638
+
639
+ def _live_provider_settings(live: Any) -> dict[str, Any]:
640
+ """The provider settings stored on the live datasource (base and create
641
+ params, which the platform splits server-side)."""
642
+ provider = live.get("provider") if isinstance(live, Mapping) else live.provider
643
+ if provider is None:
644
+ return {}
645
+ params = provider.get if isinstance(provider, Mapping) else None
646
+ out: dict[str, Any] = {}
647
+ for name in ("base_params", "create_params"):
648
+ value = params(name) if params else getattr(provider, name, None)
649
+ out.update(value or {})
650
+ return out
651
+
652
+
653
+ def _kept_live_settings(
654
+ document: Document, live: Any, secret_keys: frozenset[str] | None
655
+ ) -> dict[str, Any]:
656
+ """Live settings the document leaves out, to send back unchanged.
657
+
658
+ The backend resets every schema parameter the PUT omits to its default, so
659
+ the non-secret ones must be sent. A secret must not: a read returns it
660
+ encrypted, and the backend encrypts whatever secret it receives, so sending
661
+ it back would encrypt the ciphertext. An omitted secret keeps its stored
662
+ value. Which keys are secret comes from the platform schema; without it
663
+ nothing can be sent safely, so the update is refused."""
664
+ authored = document.spec.settings
665
+ omitted = {
666
+ k: v for k, v in _live_provider_settings(live).items() if k not in authored
667
+ }
668
+ if secret_keys is None:
669
+ if omitted:
670
+ raise ApplyError(
671
+ "provider_secrets_unknown",
672
+ "datasource",
673
+ document.meta.name,
674
+ "the stored settings "
675
+ f"{', '.join(sorted(omitted))} are not in the document, and without "
676
+ "the provider schema (provider_secret_lookup) secret ones cannot be "
677
+ "told apart; list them in the document or pass a lookup",
678
+ )
679
+ return {}
680
+ return {k: v for k, v in omitted.items() if k not in secret_keys}
681
+
682
+
683
+ def _provider_update_body(
684
+ document: Document,
685
+ resolved: Resolved,
686
+ live: Any,
687
+ secret_keys: frozenset[str] | None = None,
688
+ ) -> dict:
689
+ body = _complete_body(document, resolved, live)
690
+ body["settings"] = {
691
+ **_kept_live_settings(document, live, secret_keys),
692
+ **body.get("settings", {}),
693
+ }
694
+ identity = {
695
+ field: getattr(document.spec, field) for field in _PROVIDER_UPDATE_IDENTITY
696
+ }
697
+ body["settings"] = {**body.get("settings", {}), **identity}
698
+ return body
699
+
700
+
701
+ def _provider_create(client: Any, document: Document, resolved: Resolved) -> Any:
702
+ request = _build(
703
+ ProviderDataSourceRequest, _datasource_body(document, resolved), document
704
+ )
705
+ with _no_request_body_log():
706
+ return client.datasources.create_provider_datasource(
707
+ request.toolkit_id, request.provider_name, request
708
+ )
709
+
710
+
711
+ def _provider_update(
712
+ client: Any,
713
+ document: Document,
714
+ entity_id: str,
715
+ resolved: Resolved,
716
+ changed: frozenset[str] | None = None,
717
+ secret_keys: frozenset[str] | None = None,
718
+ ) -> Any:
719
+ live = client.datasources.get(entity_id)
720
+ request = _build(
721
+ UpdateProviderDataSourceRequest,
722
+ _provider_update_body(document, resolved, live, secret_keys),
723
+ document,
724
+ )
725
+ with _no_request_body_log():
726
+ return client.datasources.update_provider_datasource(entity_id, request)
727
+
728
+
729
+ _PROVIDER_ADAPTER = KindAdapter(
730
+ create=_provider_create,
731
+ update=_provider_update,
732
+ get=lambda client, _doc, entity_id: client.datasources.get(entity_id),
733
+ extract_id=_no_id, # the backend answers a message only; no index id
734
+ to_comparable=_datasource_view,
735
+ find_id=_find_datasource_id,
736
+ )
737
+ DATASOURCE_ADAPTERS["provider"] = _PROVIDER_ADAPTER
738
+
739
+
740
+ def _datasource_adapter(document: Document) -> KindAdapter:
741
+ ds_type = document.spec.type
742
+ adapter = DATASOURCE_ADAPTERS.get(ds_type)
743
+ if adapter is None:
744
+ raise ApplyError(
745
+ "unsupported_datasource_type",
746
+ document.meta.kind.value,
747
+ document.meta.name,
748
+ f"datasource type {ds_type!r} cannot be applied",
749
+ )
750
+ return adapter
751
+
752
+
753
+ _DATASOURCE_DISPATCH = KindAdapter(
754
+ create=lambda client, doc, resolved: _datasource_adapter(doc).create(
755
+ client, doc, resolved
756
+ ),
757
+ update=lambda client, doc, entity_id, resolved, changed=None: _datasource_adapter(
758
+ doc
759
+ ).update(client, doc, entity_id, resolved, changed),
760
+ get=lambda client, doc, entity_id: _datasource_adapter(doc).get(
761
+ client, doc, entity_id
762
+ ),
763
+ extract_id=_no_id,
764
+ to_comparable=_datasource_view,
765
+ find_id=_find_datasource_id,
766
+ )
767
+
768
+ ADAPTERS: dict[DocumentKind, KindAdapter] = {
769
+ DocumentKind.ASSISTANT: _make_adapter(
770
+ service="assistants",
771
+ body=_spec_body,
772
+ create_cls=AssistantCreateRequest,
773
+ update_cls=AssistantUpdateRequest,
774
+ check_response=_reject_declined_assistant,
775
+ update_body=_assistant_update_body,
776
+ ),
777
+ DocumentKind.SKILL: _make_adapter(
778
+ service="skills",
779
+ body=_spec_body,
780
+ create_cls=SkillCreateRequest,
781
+ update_cls=SkillUpdateRequest,
782
+ ),
783
+ DocumentKind.WORKFLOW: _make_adapter(
784
+ service="workflows",
785
+ body=_workflow_body,
786
+ create_cls=WorkflowCreateRequest,
787
+ update_cls=WorkflowUpdateRequest,
788
+ create_method="create_workflow",
789
+ update_body=_workflow_update_body,
790
+ ),
791
+ DocumentKind.CATEGORY: _make_adapter(
792
+ service="categories",
793
+ body=_spec_body,
794
+ create_cls=CategoryCreateRequest,
795
+ update_cls=CategoryUpdateRequest,
796
+ create_method="create_category",
797
+ update_method="update_category",
798
+ get_method="get_category",
799
+ ),
800
+ DocumentKind.INTEGRATION: _make_adapter(
801
+ service="integrations",
802
+ body=_integration_body,
803
+ create_cls=Integration,
804
+ update_cls=Integration,
805
+ get_fn=_get_integration,
806
+ ),
807
+ DocumentKind.DATASOURCE: _DATASOURCE_DISPATCH,
808
+ }
809
+
810
+
811
+ def adapter_for(document: Document) -> KindAdapter:
812
+ """The adapter for a document; datasources resolve by spec ``type``."""
813
+ if document.meta.kind is DocumentKind.DATASOURCE:
814
+ return _datasource_adapter(document)
815
+ return ADAPTERS[document.meta.kind]