fix(fetch): 修复钉钉来源身份与取件失败监控
build / build (push) Successful in 1m17s

This commit is contained in:
姚章浩
2026-10-27 14:36:24 +08:00
parent 1b09f7d35b
commit 74aef1e373
8 changed files with 211 additions and 9 deletions
+48 -1
View File
@@ -371,8 +371,55 @@ def dingtalk_local_export(manifest):
return str(candidate), fresh
def dingtalk_live_raw_key(manifest):
"""Resolve in the configured source; names locate folders, never file identity."""
from live_catalog_refresh import dingtalk_root_key
from source_catalog_import import node_id as catalog_node_id, safe_relative_path
from dws_dingtalk_scan import normalise
match = re.fullmatch(r"spaces/([A-Za-z0-9_-]+)\?space=([A-Za-z0-9_-]+)", manifest['source_root'])
if not match:
raise FetchError('DingTalk source root is invalid', retryable=False, code='source_identity')
root_id, space_id = match.groups()
try:
source_key = 'dingtalk-' + dingtalk_root_key(manifest['connection_id'], space_id)
parts = safe_relative_path(manifest['relative_path']).split('/')
except (OSError, ValueError, RuntimeError):
raise FetchError('DingTalk source identity cannot be resolved', retryable=False, code='source_identity')
folder = ''
for index in range(len(parts)):
drive = space_id.isdigit()
args = ['drive', '+list', '--space-id', space_id] if drive else ['wiki', '+node-list', '--workspace', space_id]
args += ['--page-all', '--limit', '50', '--max-items', '10000', '--page-limit', '200']
if folder:
args += ['--folder', folder]
payload, verdict = dws_run(args, timeout=180)
if not verdict['ok']:
raise _dws_error(verdict)
data = payload.get('data', {}) if isinstance(payload, dict) else {}
entries = data.get('files' if drive else 'nodes')
if not isinstance(entries, list) or data.get('hasMore') is not False or data.get('autoPageComplete') is not True:
raise FetchError('DingTalk directory response is incomplete', retryable=True, code='source_lookup_incomplete')
matches = []
for entry in entries:
raw, node, is_folder = normalise(entry, folder or root_id)
if index == len(parts) - 1:
if not is_folder and catalog_node_id(source_key, raw) == manifest['node_id']:
matches.append(raw)
elif is_folder and node['name'] == parts[index]:
matches.append(raw)
if len(matches) != 1:
# A missing/ambiguous path is not evidence that the source file was deleted.
raise FetchError('DingTalk node identity unresolved; refresh 来源目录 before retrying',
retryable=False, code='source_node_unresolved')
folder = matches[0]
return folder, 'file'
def dingtalk_raw_keys(manifest):
"""Recover the dentry uuid behind a node id via the scanner inventory."""
"""Use current source coordinates; retain inventory support for old manifests."""
if manifest.get('source_root'):
return dingtalk_live_raw_key(manifest)
state_path = pathlib.Path("/sources/dingtalk/data/dingtalk-internal/inventory-state.json")
state = json.loads(state_path.read_text(encoding="utf-8"))
roots = state.get("roots") or {}
+72
View File
@@ -69,6 +69,78 @@ class DingTalkOnlineDocumentExportTest(unittest.TestCase):
download.assert_called_once_with("https://oss.example/result.docx", {}, 180, 1_000_000)
class DingTalkCurrentIdentityTest(unittest.TestCase):
def test_current_source_resolves_live_node_not_same_named_legacy_node(self):
from source_catalog_import import node_id, stable_connection_id
source = 'dingtalk-space-workspace1'
manifest = {
'source_root': 'spaces/workspace1?space=workspace1',
'connection_id': stable_connection_id(source),
'source_name': 'Renamed KB', 'node_id': node_id(source, 'current-raw'),
'relative_path': 'Folder/Manual.adoc', 'name': 'Manual.adoc',
}
legacy = {'roots': {'space-legacy': {'live_space_name': 'Renamed KB', 'nodes': {
'wrong-raw': {'name': 'Manual.adoc', 'dentry_type': 'file'},
}}}}
pages = [
[{'nodeId': 'folder-raw', 'name': 'Folder', 'nodeType': 'folder'}],
[{'nodeId': 'wrong-raw', 'name': 'Manual', 'nodeType': 'file', 'extension': 'adoc'},
{'nodeId': 'current-raw', 'name': 'Manual', 'nodeType': 'file', 'extension': 'adoc'}],
]
responses = [({'data': {'nodes': page, 'hasMore': False, 'autoPageComplete': True}}, {'ok': True}) for page in pages]
with mock.patch.object(pathlib.Path, 'read_text', return_value=json.dumps(legacy)), \
mock.patch.object(artifact_fetch, 'dws_run', side_effect=responses) as listing:
self.assertEqual(artifact_fetch.dingtalk_raw_keys(manifest), ('current-raw', 'file'))
self.assertEqual(listing.call_count, 2)
self.assertIn('workspace1', listing.call_args_list[0].args[0])
self.assertEqual(listing.call_args_list[1].args[0][-2:], ['--folder', 'folder-raw'])
def test_identity_and_incomplete_listing_fail_closed_without_false_deletion(self):
from source_catalog_import import node_id, stable_connection_id
source = 'dingtalk-space-workspace1'
manifest = {'source_root': 'spaces/workspace1?space=workspace1',
'connection_id': stable_connection_id(source), 'node_id': node_id(source, 'right'),
'name': 'Manual.adoc', 'relative_path': 'Manual.adoc'}
wrong = {'nodeId': 'wrong', 'name': 'Manual.adoc', 'nodeType': 'file'}
cases = [
({'nodes': [wrong], 'hasMore': False, 'autoPageComplete': True}, 'source_node_unresolved'),
({'nodes': [], 'hasMore': True, 'autoPageComplete': False}, 'source_lookup_incomplete'),
({'nodes': [], 'hasMore': False}, 'source_lookup_incomplete'),
]
for data, code in cases:
with self.subTest(code=code, data=data), mock.patch.object(artifact_fetch, 'dws_run', return_value=({'data': data}, {'ok': True})):
with self.assertRaises(artifact_fetch.FetchError) as failure:
artifact_fetch.dingtalk_raw_keys(manifest)
self.assertNotIsInstance(failure.exception, artifact_fetch.MissingSource)
self.assertEqual(failure.exception.code, code)
with mock.patch.object(artifact_fetch, 'dws_run') as call:
with self.assertRaises(artifact_fetch.FetchError):
artifact_fetch.dingtalk_raw_keys({**manifest, 'source_root': 'invalid'})
call.assert_not_called()
verdict = artifact_fetch.dws_error_map.classify({'error': {'message': 'invalidParameter.authCode.notFound'}})
with mock.patch.object(artifact_fetch, 'dws_run', return_value=(None, verdict)):
with self.assertRaises(artifact_fetch.FetchError) as failure:
artifact_fetch.dingtalk_raw_keys(manifest)
self.assertEqual(failure.exception.code, 'credentials')
self.assertFalse(failure.exception.retryable)
def test_legacy_namespace_and_drive_keep_their_own_identity(self):
from source_catalog_import import node_id, stable_connection_id
for space, root_key, drive in [('workspace1', 'space-old', False), ('12345', 'space-12345', True)]:
source = 'dingtalk-' + root_key
manifest = {'source_root': f'spaces/{space}?space={space}',
'connection_id': stable_connection_id(source), 'node_id': node_id(source, 'right'),
'name': 'Manual.adoc', 'relative_path': 'Manual.adoc'}
data = {'files' if drive else 'nodes': [{'nodeId': 'right', 'name': 'Manual', 'type': 'file'}],
'hasMore': False, 'autoPageComplete': True}
with self.subTest(space=space), \
mock.patch.object(pathlib.Path, 'read_text', return_value=json.dumps({'roots': {'space-old': {}}})), \
mock.patch.object(artifact_fetch, 'dws_run', return_value=({'data': data}, {'ok': True})) as call:
self.assertEqual(artifact_fetch.dingtalk_raw_keys(manifest), ('right', 'file'))
self.assertEqual(call.call_args.args[0][0], 'drive' if drive else 'wiki')
class DingTalkDwsFetcherTest(unittest.TestCase):
"""dws 取件器:路由、回落语义、以及"结果 JSON 形状不得变化"的契约锁定。"""