-
Notifications
You must be signed in to change notification settings - Fork 436
Expand file tree
/
Copy pathOneLakeService.cs
More file actions
1875 lines (1604 loc) · 80 KB
/
OneLakeService.cs
File metadata and controls
1875 lines (1604 loc) · 80 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http.Headers;
using System.Text;
using System.Text.Json;
using System.Xml.Linq;
using Azure.Core;
using Azure.Identity;
using Fabric.Mcp.Tools.OneLake.Models;
namespace Fabric.Mcp.Tools.OneLake.Services;
public class OneLakeService(HttpClient httpClient, TokenCredential? credential = null) : IOneLakeService
{
private readonly HttpClient _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
private readonly TokenCredential _credential = credential ?? new DefaultAzureCredential();
private const string UserAgentHeaderName = "User-Agent";
private const string UserAgentHeaderValue = "OneLake MCP";
private readonly ConcurrentDictionary<string, ConcurrentDictionary<string, string>> _itemIdentifierCache = new(StringComparer.OrdinalIgnoreCase);
public async Task<string> ResolveItemIdentifierAsync(string workspaceId, string itemIdentifier, CancellationToken cancellationToken = default)
{
var normalizedWorkspaceId = NormalizeWorkspaceIdentifier(workspaceId);
var normalizedItemInput = NormalizeItemIdentifier(itemIdentifier);
if (Guid.TryParse(normalizedItemInput, out _))
{
return normalizedItemInput;
}
if (normalizedItemInput.Contains('.'))
{
return normalizedItemInput.TrimEnd('/');
}
var workspaceCache = GetWorkspaceItemCache(normalizedWorkspaceId);
if (workspaceCache.TryGetValue(normalizedItemInput, out var cachedIdentifier))
{
return cachedIdentifier;
}
var items = await ListOneLakeItemsAsync(normalizedWorkspaceId, cancellationToken: cancellationToken);
foreach (var item in items)
{
if (string.IsNullOrWhiteSpace(item.Id))
{
continue;
}
var artifactId = NormalizeItemIdentifier(item.Id);
workspaceCache.TryAdd(artifactId, artifactId);
if (!string.IsNullOrWhiteSpace(item.DisplayName))
{
workspaceCache.TryAdd(item.DisplayName.Trim(), artifactId);
}
var artifactGuid = item.Metadata?.ArtifactId;
if (!string.IsNullOrWhiteSpace(artifactGuid))
{
workspaceCache.TryAdd(artifactGuid.Trim(), artifactId);
}
}
if (workspaceCache.TryGetValue(normalizedItemInput, out cachedIdentifier))
{
return cachedIdentifier;
}
throw new InvalidOperationException($"Unable to resolve item '{itemIdentifier}' in workspace '{workspaceId}'. Provide the full item identifier including its suffix, for example 'ItemName.Lakehouse'.");
}
private ConcurrentDictionary<string, string> GetWorkspaceItemCache(string workspaceId)
{
return _itemIdentifierCache.GetOrAdd(workspaceId, static _ => new ConcurrentDictionary<string, string>(StringComparer.OrdinalIgnoreCase));
}
private static string NormalizeWorkspaceIdentifier(string workspaceId)
{
if (string.IsNullOrWhiteSpace(workspaceId))
{
throw new ArgumentException("Workspace identifier is required.", nameof(workspaceId));
}
return workspaceId.Trim();
}
private static string NormalizeItemIdentifier(string itemIdentifier)
{
if (string.IsNullOrWhiteSpace(itemIdentifier))
{
throw new ArgumentException("Item identifier is required.", nameof(itemIdentifier));
}
return itemIdentifier.Trim().TrimEnd('/');
}
private async Task<(string WorkspaceId, string ItemId)> GetNormalizedIdentifiersAsync(string workspaceId, string itemId, CancellationToken cancellationToken)
{
var normalizedWorkspaceId = NormalizeWorkspaceIdentifier(workspaceId);
var normalizedItemId = await ResolveItemIdentifierAsync(normalizedWorkspaceId, itemId, cancellationToken);
return (normalizedWorkspaceId, normalizedItemId);
}
// Workspace Operations
public async Task<IEnumerable<Workspace>> ListOneLakeWorkspacesAsync(string? continuationToken = null, CancellationToken cancellationToken = default)
{
var url = $"{OneLakeEndpoints.OneLakeDataPlaneBaseUrl}/?comp=list";
if (!string.IsNullOrEmpty(continuationToken))
{
url += $"&continuationToken={Uri.EscapeDataString(continuationToken)}";
}
var response = await SendOneLakeApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
using var reader = new StreamReader(response);
var xmlContent = await reader.ReadToEndAsync(cancellationToken);
try
{
var doc = XDocument.Parse(xmlContent);
var containers = doc.Root?.Element("Containers")?.Elements("Container") ?? [];
var workspaces = containers.Select(container =>
{
var workspace = new Workspace
{
Id = container.Element("Name")?.Value ?? string.Empty,
DisplayName = container.Element("Name")?.Value ?? string.Empty
};
var propertiesElement = container.Element("Properties");
if (propertiesElement != null)
{
workspace.Properties = new WorkspaceProperties();
var lastModifiedString = propertiesElement.Element("Last-Modified")?.Value;
if (!string.IsNullOrEmpty(lastModifiedString) && DateTime.TryParse(lastModifiedString, out var lastModified))
{
workspace.Properties.LastModified = lastModified;
}
}
var metadataElement = container.Element("Metadata");
if (metadataElement != null)
{
workspace.Metadata = new WorkspaceMetadata
{
RegionalServiceEndpoint = metadataElement.Element("RegionalServiceEndpoint")?.Value,
WorkspaceObjectId = metadataElement.Element("WorkspaceObjectId")?.Value,
WorkspacePortalUrl = metadataElement.Element("WorkspacePortalUrl")?.Value
};
}
return workspace;
}).ToList();
return workspaces;
}
catch (Exception ex)
{
throw new InvalidOperationException("Failed to parse OneLake workspace list response.", ex);
}
}
public async Task<string> ListOneLakeWorkspacesXmlAsync(string? continuationToken = null, CancellationToken cancellationToken = default)
{
var url = $"{OneLakeEndpoints.OneLakeDataPlaneBaseUrl}/?comp=list";
if (!string.IsNullOrEmpty(continuationToken))
{
url += $"&continuationToken={Uri.EscapeDataString(continuationToken)}";
}
var response = await SendOneLakeApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
using var reader = new StreamReader(response);
return await reader.ReadToEndAsync(cancellationToken);
}
// Item Operations
public async Task<OneLakeItem> CreateItemAsync(string workspaceId, CreateItemRequest request, CancellationToken cancellationToken = default)
{
var url = $"{OneLakeEndpoints.GetFabricApiBaseUrl()}/workspaces/{workspaceId}/items";
var jsonContent = JsonSerializer.Serialize(request, OneLakeJsonContext.Default.CreateItemRequest);
var response = await SendFabricApiRequestAsync(HttpMethod.Post, url, jsonContent, null, cancellationToken);
return await JsonSerializer.DeserializeAsync<OneLakeItem>(response, OneLakeJsonContext.Default.OneLakeItem, cancellationToken) ?? new OneLakeItem();
}
// Private helper method for internal use
private async Task<Workspace> GetWorkspaceAsync(string workspaceId, CancellationToken cancellationToken = default)
{
var url = $"{OneLakeEndpoints.GetFabricApiBaseUrl()}/workspaces/{workspaceId}";
var response = await SendFabricApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
return await JsonSerializer.DeserializeAsync<Workspace>(response, OneLakeJsonContext.Default.Workspace, cancellationToken) ?? new Workspace();
}
// Data Operations (OneLake Data Plane)
public async Task<OneLakeFileInfo> GetFileInfoAsync(string workspaceId, string itemId, string filePath, CancellationToken cancellationToken = default)
{
ValidatePathForTraversal(filePath, nameof(filePath));
var (normalizedWorkspaceId, normalizedItemId) = await GetNormalizedIdentifiersAsync(workspaceId, itemId, cancellationToken);
var url = $"{OneLakeEndpoints.OneLakeDataPlaneBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}/Files/{filePath.TrimStart('/')}";
var response = await SendDataPlaneRequestAsync(HttpMethod.Head, url, cancellationToken: cancellationToken);
return new OneLakeFileInfo
{
Name = Path.GetFileName(filePath),
Path = filePath,
IsDirectory = false,
Size = GetContentLength(response.Headers),
LastModified = GetLastModified(response.Headers),
ContentType = response.Content.Headers.ContentType?.ToString(),
ETag = response.Headers.ETag?.ToString()
};
}
public async Task<IEnumerable<OneLakeFileInfo>> ListBlobsAsync(string workspaceId, string itemId, string? path = null, bool recursive = false, CancellationToken cancellationToken = default)
{
if (path is not null)
ValidatePathForTraversal(path, nameof(path));
var (normalizedWorkspaceId, normalizedItemId) = await GetNormalizedIdentifiersAsync(workspaceId, itemId, cancellationToken);
// If no path is specified, intelligently discover and search top-level folders
if (string.IsNullOrEmpty(path))
{
return await ListBlobsIntelligentAsync(normalizedWorkspaceId, normalizedItemId, recursive, cancellationToken);
}
// Use the OneLake blob endpoint to list files for specific path
var url = $"{OneLakeEndpoints.OneLakeDataPlaneBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}";
// If path is specified, check if it's a top-level folder (Tables, Files, etc.)
// or a sub-path within Files
var trimmedPath = path.TrimStart('/');
if (trimmedPath.StartsWith("Files/", StringComparison.OrdinalIgnoreCase))
{
// Path already includes Files prefix
url += $"/{trimmedPath}";
}
else if (trimmedPath.Equals("Files", StringComparison.OrdinalIgnoreCase))
{
// Explicitly requesting Files folder
url += "/Files";
}
else if (IsTopLevelFolder(trimmedPath))
{
// Top-level folder like Tables, Files, etc.
url += $"/{trimmedPath}";
}
else
{
// Assume it's a sub-path within Files for backward compatibility
url += $"/Files/{trimmedPath}";
}
url += $"?restype=container&comp=list";
if (recursive)
{
url += "&recursive=true";
}
var response = await SendDataPlaneRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
var content = await response.Content.ReadAsStringAsync(cancellationToken);
// Parse XML response to extract file information
var files = ParseBlobListResponse(content);
return files.OrderBy(f => f.IsDirectory ? 0 : 1).ThenBy(f => f.Name);
}
private static bool IsTopLevelFolder(string path)
{
// Check if the path represents a top-level folder in OneLake
// Common top-level folders include Tables, Files, and potentially others
var folder = path.Split('/')[0]; // Get the first segment
return folder.Equals("Tables", StringComparison.OrdinalIgnoreCase) ||
folder.Equals("Files", StringComparison.OrdinalIgnoreCase);
}
public async Task<IEnumerable<OneLakeFileInfo>> ListBlobsIntelligentAsync(string workspaceId, string itemId, bool recursive, CancellationToken cancellationToken)
{
var (normalizedWorkspaceId, normalizedItemId) = await GetNormalizedIdentifiersAsync(workspaceId, itemId, cancellationToken);
// Intelligent discovery: Try to list contents from both Files and Tables folders
var allFiles = new List<OneLakeFileInfo>();
var topLevelFolders = new[] { "Files", "Tables" };
foreach (var folder in topLevelFolders)
{
try
{
var url = $"{OneLakeEndpoints.OneLakeDataPlaneBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}/{folder}";
url += $"?restype=container&comp=list";
if (recursive)
{
url += "&recursive=true";
}
var response = await SendDataPlaneRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
var content = await response.Content.ReadAsStringAsync(cancellationToken);
// Parse XML response to extract file information
var files = ParseBlobListResponse(content);
allFiles.AddRange(files);
}
catch (HttpRequestException ex) when (ex.Message.Contains("404"))
{
// Folder doesn't exist, skip it
continue;
}
catch (Exception)
{
// Other errors, skip this folder but continue with others
continue;
}
}
return allFiles.OrderBy(f => f.IsDirectory ? 0 : 1).ThenBy(f => f.Name);
}
public async Task<TableConfigurationResult> GetTableConfigurationAsync(string workspaceIdentifier, string itemIdentifier, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(workspaceIdentifier))
{
throw new ArgumentException("Workspace identifier is required.", nameof(workspaceIdentifier));
}
if (string.IsNullOrWhiteSpace(itemIdentifier))
{
throw new ArgumentException("Item identifier is required.", nameof(itemIdentifier));
}
var (normalizedWorkspaceId, normalizedItemIdentifier, _, warehouseQueryValue) = await GetWarehousePrefixAsync(workspaceIdentifier, itemIdentifier, cancellationToken);
var url = $"{OneLakeEndpoints.OneLakeTableApiBaseUrl}/iceberg/v1/config?warehouse={warehouseQueryValue}";
using var responseStream = await SendOneLakeApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
using var reader = new StreamReader(responseStream);
var rawResponse = await reader.ReadToEndAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(rawResponse))
{
throw new InvalidOperationException("Received empty table configuration response.");
}
using var document = JsonDocument.Parse(rawResponse);
var configuration = document.RootElement.Clone();
return new TableConfigurationResult(normalizedWorkspaceId, normalizedItemIdentifier, configuration, rawResponse);
}
public async Task<TableNamespaceListResult> ListTableNamespacesAsync(string workspaceIdentifier, string itemIdentifier, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(workspaceIdentifier))
{
throw new ArgumentException("Workspace identifier is required.", nameof(workspaceIdentifier));
}
if (string.IsNullOrWhiteSpace(itemIdentifier))
{
throw new ArgumentException("Item identifier is required.", nameof(itemIdentifier));
}
var (normalizedWorkspaceId, normalizedItemIdentifier, warehousePrefix, _) = await GetWarehousePrefixAsync(workspaceIdentifier, itemIdentifier, cancellationToken);
var url = $"{OneLakeEndpoints.OneLakeTableApiBaseUrl}/iceberg/v1/{warehousePrefix}/namespaces";
using var responseStream = await SendOneLakeApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
using var reader = new StreamReader(responseStream);
var rawResponse = await reader.ReadToEndAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(rawResponse))
{
throw new InvalidOperationException("Received empty table namespace response.");
}
using var document = JsonDocument.Parse(rawResponse);
var namespaces = document.RootElement.Clone();
return new TableNamespaceListResult(normalizedWorkspaceId, normalizedItemIdentifier, namespaces, rawResponse);
}
public async Task<TableNamespaceGetResult> GetTableNamespaceAsync(string workspaceIdentifier, string itemIdentifier, string namespaceName, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(workspaceIdentifier))
{
throw new ArgumentException("Workspace identifier is required.", nameof(workspaceIdentifier));
}
if (string.IsNullOrWhiteSpace(itemIdentifier))
{
throw new ArgumentException("Item identifier is required.", nameof(itemIdentifier));
}
if (string.IsNullOrWhiteSpace(namespaceName))
{
throw new ArgumentException("Namespace name is required.", nameof(namespaceName));
}
var trimmedNamespace = namespaceName.Trim();
if (string.IsNullOrEmpty(trimmedNamespace))
{
throw new ArgumentException("Namespace name cannot be empty.", nameof(namespaceName));
}
var (normalizedWorkspaceId, normalizedItemIdentifier, warehousePrefix, _) = await GetWarehousePrefixAsync(workspaceIdentifier, itemIdentifier, cancellationToken);
var encodedNamespace = Uri.EscapeDataString(trimmedNamespace);
var url = $"{OneLakeEndpoints.OneLakeTableApiBaseUrl}/iceberg/v1/{warehousePrefix}/namespaces/{encodedNamespace}";
using var responseStream = await SendOneLakeApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
using var reader = new StreamReader(responseStream);
var rawResponse = await reader.ReadToEndAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(rawResponse))
{
throw new InvalidOperationException("Received empty table namespace response.");
}
using var document = JsonDocument.Parse(rawResponse);
var definition = document.RootElement.Clone();
return new TableNamespaceGetResult(normalizedWorkspaceId, normalizedItemIdentifier, trimmedNamespace, definition, rawResponse);
}
public async Task<TableListResult> ListTablesAsync(string workspaceIdentifier, string itemIdentifier, string namespaceName, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(workspaceIdentifier))
{
throw new ArgumentException("Workspace identifier is required.", nameof(workspaceIdentifier));
}
if (string.IsNullOrWhiteSpace(itemIdentifier))
{
throw new ArgumentException("Item identifier is required.", nameof(itemIdentifier));
}
if (string.IsNullOrWhiteSpace(namespaceName))
{
throw new ArgumentException("Namespace name is required.", nameof(namespaceName));
}
var trimmedNamespace = namespaceName.Trim();
if (string.IsNullOrEmpty(trimmedNamespace))
{
throw new ArgumentException("Namespace name cannot be empty.", nameof(namespaceName));
}
var (normalizedWorkspaceId, normalizedItemIdentifier, warehousePrefix, _) = await GetWarehousePrefixAsync(workspaceIdentifier, itemIdentifier, cancellationToken);
var encodedNamespace = Uri.EscapeDataString(trimmedNamespace);
var url = $"{OneLakeEndpoints.OneLakeTableApiBaseUrl}/iceberg/v1/{warehousePrefix}/namespaces/{encodedNamespace}/tables";
using var responseStream = await SendOneLakeApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
using var reader = new StreamReader(responseStream);
var rawResponse = await reader.ReadToEndAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(rawResponse))
{
throw new InvalidOperationException("Received empty table list response.");
}
using var document = JsonDocument.Parse(rawResponse);
var tables = document.RootElement.Clone();
return new TableListResult(normalizedWorkspaceId, normalizedItemIdentifier, trimmedNamespace, tables, rawResponse);
}
public async Task<TableGetResult> GetTableAsync(string workspaceIdentifier, string itemIdentifier, string namespaceName, string tableName, CancellationToken cancellationToken = default)
{
if (string.IsNullOrWhiteSpace(workspaceIdentifier))
{
throw new ArgumentException("Workspace identifier is required.", nameof(workspaceIdentifier));
}
if (string.IsNullOrWhiteSpace(itemIdentifier))
{
throw new ArgumentException("Item identifier is required.", nameof(itemIdentifier));
}
if (string.IsNullOrWhiteSpace(namespaceName))
{
throw new ArgumentException("Namespace name is required.", nameof(namespaceName));
}
if (string.IsNullOrWhiteSpace(tableName))
{
throw new ArgumentException("Table name is required.", nameof(tableName));
}
var trimmedNamespace = namespaceName.Trim();
var trimmedTableName = tableName.Trim();
if (string.IsNullOrEmpty(trimmedNamespace))
{
throw new ArgumentException("Namespace name cannot be empty.", nameof(namespaceName));
}
if (string.IsNullOrEmpty(trimmedTableName))
{
throw new ArgumentException("Table name cannot be empty.", nameof(tableName));
}
var (normalizedWorkspaceId, normalizedItemIdentifier, warehousePrefix, _) = await GetWarehousePrefixAsync(workspaceIdentifier, itemIdentifier, cancellationToken);
var encodedNamespace = Uri.EscapeDataString(trimmedNamespace);
var encodedTable = Uri.EscapeDataString(trimmedTableName);
var url = $"{OneLakeEndpoints.OneLakeTableApiBaseUrl}/iceberg/v1/{warehousePrefix}/namespaces/{encodedNamespace}/tables/{encodedTable}";
using var responseStream = await SendOneLakeApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
using var reader = new StreamReader(responseStream);
var rawResponse = await reader.ReadToEndAsync(cancellationToken);
if (string.IsNullOrWhiteSpace(rawResponse))
{
throw new InvalidOperationException("Received empty table response.");
}
using var document = JsonDocument.Parse(rawResponse);
var tableDefinition = document.RootElement.Clone();
return new TableGetResult(normalizedWorkspaceId, normalizedItemIdentifier, trimmedNamespace, trimmedTableName, tableDefinition, rawResponse);
}
private List<OneLakeFileInfo> ParseBlobListResponse(string xmlContent)
{
var files = new List<OneLakeFileInfo>();
try
{
var doc = XDocument.Parse(xmlContent);
var ns = doc.Root?.GetDefaultNamespace() ?? XNamespace.None;
// Parse blob elements (files and directories)
var blobs = doc.Descendants(ns + "Blob");
foreach (var blob in blobs)
{
var nameElement = blob.Element(ns + "Name");
var propertiesElement = blob.Element(ns + "Properties");
if (nameElement?.Value == null || propertiesElement == null)
continue;
var fileName = nameElement.Value;
var lastModified = propertiesElement.Element(ns + "Last-Modified")?.Value;
var contentLength = propertiesElement.Element(ns + "Content-Length")?.Value;
var contentType = propertiesElement.Element(ns + "Content-Type")?.Value;
var resourceType = propertiesElement.Element(ns + "ResourceType")?.Value;
var size = long.TryParse(contentLength, out var parsedSize) ? parsedSize : 0;
// Use ResourceType to determine if this is a directory
var isDirectory = string.Equals(resourceType, "directory", StringComparison.OrdinalIgnoreCase);
files.Add(new OneLakeFileInfo
{
Name = Path.GetFileName(fileName),
Path = fileName,
Size = size,
LastModified = DateTime.TryParse(lastModified, out var modifiedDate) ? modifiedDate : null,
ContentType = isDirectory ? "application/x-directory" : (contentType ?? "application/octet-stream"),
IsDirectory = isDirectory
});
}
// Parse blob prefixes (directories) - Note: OneLake typically doesn't return these
var blobPrefixes = doc.Descendants(ns + "BlobPrefix");
foreach (var prefix in blobPrefixes)
{
var nameElement = prefix.Element(ns + "Name");
if (nameElement?.Value != null)
{
var dirName = nameElement.Value.TrimEnd('/');
files.Add(new OneLakeFileInfo
{
Name = Path.GetFileName(dirName),
Path = dirName,
Size = 0,
LastModified = null,
ContentType = "application/x-directory",
IsDirectory = true
});
}
}
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to parse OneLake file listing response: {ex.Message}", ex);
}
return files;
}
public async Task<List<FileSystemItem>> ListPathIntelligentAsync(string workspaceId, string itemId, bool recursive, CancellationToken cancellationToken)
{
var (normalizedWorkspaceId, normalizedItemId) = await GetNormalizedIdentifiersAsync(workspaceId, itemId, cancellationToken);
// Intelligent discovery: Try to list contents from both Files and Tables folders using DFS API
var allItems = new List<FileSystemItem>();
var topLevelFolders = new[] { "Files", "Tables" };
foreach (var folder in topLevelFolders)
{
try
{
var url = $"{OneLakeEndpoints.OneLakeDataPlaneDfsBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}/{folder}";
url += $"?resource=filesystem&recursive={recursive.ToString().ToLowerInvariant()}";
var response = await SendDataPlaneRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
var content = await response.Content.ReadAsStringAsync(cancellationToken);
var items = ParsePathListResponse(content);
allItems.AddRange(items);
}
catch (HttpRequestException ex) when (ex.Message.Contains("404"))
{
// Folder doesn't exist, skip it
continue;
}
catch (Exception)
{
// Other errors, skip this folder but continue with others
continue;
}
}
return allItems.OrderBy(f => f.Type == "directory" ? 0 : 1).ThenBy(f => f.Name).ToList();
}
private List<FileSystemItem> ParsePathListResponse(string jsonContent)
{
var fileSystemItems = new List<FileSystemItem>();
try
{
// Parse JSON response from ADLS Gen2 API
using var document = JsonDocument.Parse(jsonContent);
var root = document.RootElement;
if (root.TryGetProperty("paths", out var pathsElement))
{
foreach (var pathItem in pathsElement.EnumerateArray())
{
var name = pathItem.TryGetProperty("name", out var nameElement) ? nameElement.GetString() : "";
var isDirectory = false;
if (pathItem.TryGetProperty("isDirectory", out var isDirElement))
{
// Handle both boolean and string representations
if (isDirElement.ValueKind == JsonValueKind.True)
{
isDirectory = true;
}
else if (isDirElement.ValueKind == JsonValueKind.False)
{
isDirectory = false;
}
else if (isDirElement.ValueKind == JsonValueKind.String)
{
isDirectory = bool.TryParse(isDirElement.GetString(), out var boolValue) && boolValue;
}
}
var contentLength = 0L;
if (pathItem.TryGetProperty("contentLength", out var lengthElement))
{
if (lengthElement.ValueKind == JsonValueKind.Number)
{
contentLength = lengthElement.GetInt64();
}
else if (lengthElement.ValueKind == JsonValueKind.String)
{
long.TryParse(lengthElement.GetString(), out contentLength);
}
}
var lastModified = pathItem.TryGetProperty("lastModified", out var modElement)
? DateTime.TryParse(modElement.GetString(), out var modDate) ? modDate : (DateTime?)null
: null;
var etag = pathItem.TryGetProperty("etag", out var etagElement) ? etagElement.GetString() : null;
var permissions = pathItem.TryGetProperty("permissions", out var permsElement) ? permsElement.GetString() : null;
var owner = pathItem.TryGetProperty("owner", out var ownerElement) ? ownerElement.GetString() : null;
var group = pathItem.TryGetProperty("group", out var groupElement) ? groupElement.GetString() : null;
if (!string.IsNullOrEmpty(name))
{
var item = new FileSystemItem
{
Name = Path.GetFileName(name),
Path = name,
Type = isDirectory ? "directory" : "file",
Size = isDirectory ? null : contentLength,
LastModified = lastModified,
ContentType = isDirectory ? "application/x-directory" : "application/octet-stream",
ETag = etag,
Permissions = permissions,
Owner = owner,
Group = group,
Children = null
};
fileSystemItems.Add(item);
}
}
}
}
catch (JsonException ex)
{
throw new InvalidOperationException($"Failed to parse OneLake path listing response: {ex.Message}", ex);
}
return fileSystemItems;
}
public async Task<List<FileSystemItem>> ListPathAsync(string workspaceId, string itemId, string? path = null, bool recursive = false, CancellationToken cancellationToken = default)
{
if (path is not null)
ValidatePathForTraversal(path, nameof(path));
var (normalizedWorkspaceId, normalizedItemId) = await GetNormalizedIdentifiersAsync(workspaceId, itemId, cancellationToken);
// If no path is specified, intelligently discover and search top-level folders
if (string.IsNullOrEmpty(path))
{
return await ListPathIntelligentAsync(normalizedWorkspaceId, normalizedItemId, recursive, cancellationToken);
}
// Use ADLS Gen2 filesystem API format instead of blob container format
var url = $"{OneLakeEndpoints.OneLakeDataPlaneDfsBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}";
// If path is specified, check if it's a top-level folder (Tables, Files, etc.)
// or a sub-path within Files
var trimmedPath = path.TrimStart('/');
if (trimmedPath.StartsWith("Files/", StringComparison.OrdinalIgnoreCase))
{
// Path already includes Files prefix
url += $"/{trimmedPath}";
}
else if (trimmedPath.Equals("Files", StringComparison.OrdinalIgnoreCase))
{
// Explicitly requesting Files folder
url += "/Files";
}
else if (IsTopLevelFolder(trimmedPath))
{
// Top-level folder like Tables, Files, etc.
url += $"/{trimmedPath}";
}
else
{
// Assume it's a sub-path within Files for backward compatibility
url += $"/Files/{trimmedPath}";
}
url += $"?resource=filesystem&recursive={recursive.ToString().ToLowerInvariant()}";
var response = await SendDataPlaneRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
var content = await response.Content.ReadAsStringAsync(cancellationToken);
var fileSystemItems = ParsePathListResponse(content);
return fileSystemItems.OrderBy(f => f.Type == "directory" ? 0 : 1).ThenBy(f => f.Name).ToList();
}
private List<FileSystemItem> BuildHierarchicalStructure(List<FileSystemItem> flatItems, string basePath)
{
var root = new List<FileSystemItem>();
var pathPrefix = basePath.TrimEnd('/') + "/";
// Group items by their immediate parent directory
var grouped = flatItems
.Where(item => item.Path.StartsWith(pathPrefix, StringComparison.OrdinalIgnoreCase) || item.Path == basePath.TrimEnd('/'))
.GroupBy(item =>
{
var relativePath = item.Path.Substring(pathPrefix.Length);
var firstSlash = relativePath.IndexOf('/');
return firstSlash == -1 ? "" : relativePath.Substring(0, firstSlash);
});
foreach (var group in grouped)
{
if (string.IsNullOrEmpty(group.Key))
{
// Direct children of the base path
root.AddRange(group);
}
else
{
// Create directory entry with children
var dirPath = $"{pathPrefix}{group.Key}";
var directoryItem = group.FirstOrDefault(item => item.Path == dirPath && item.Type == "directory");
if (directoryItem == null)
{
directoryItem = new FileSystemItem
{
Name = group.Key,
Path = dirPath,
Type = "directory",
Size = null,
LastModified = null,
ContentType = "application/x-directory"
};
}
directoryItem.Children = group.Where(item => item.Path != dirPath).ToList();
root.Add(directoryItem);
}
}
return root.OrderBy(f => f.Type == "directory" ? 0 : 1).ThenBy(f => f.Name).ToList();
}
public async Task<IEnumerable<OneLakeItem>> ListOneLakeItemsAsync(string workspaceId, string? continuationToken = null, CancellationToken cancellationToken = default)
{
var xmlContent = await ExecuteWithWorkspaceFallbackAsync(
workspaceId,
async identifier =>
{
var url = $"{OneLakeEndpoints.OneLakeDataPlaneBaseUrl}/{identifier}?delimiter=/&restype=container&comp=list";
if (!string.IsNullOrEmpty(continuationToken))
{
url += $"&continuationToken={Uri.EscapeDataString(continuationToken)}";
}
var response = await SendOneLakeApiRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
using var reader = new StreamReader(response);
return await reader.ReadToEndAsync(cancellationToken);
},
cancellationToken);
try
{
var doc = XDocument.Parse(xmlContent);
// For container listing with comp=list, Azure Storage returns different XML structure
// Try various possible XML structures based on Azure Storage Blob Service API
var items = new List<OneLakeItem>();
// Option 1: Try <EnumerationResults><Blobs><BlobPrefix> (OneLake uses BlobPrefix)
var blobPrefixes = doc.Root?.Element("Blobs")?.Elements("BlobPrefix");
if (blobPrefixes != null && blobPrefixes.Any())
{
items.AddRange(ParseBlobPrefixElements(blobPrefixes, workspaceId));
}
// Option 2: Try <EnumerationResults><Blobs><Blob> (fallback for regular blobs)
if (!items.Any())
{
var blobs = doc.Root?.Element("Blobs")?.Elements("Blob");
if (blobs != null && blobs.Any())
{
items.AddRange(ParseBlobElements(blobs, workspaceId));
}
}
// Option 2: Try <EnumerationResults><Containers><Container> (like workspace listing)
if (!items.Any())
{
var containers = doc.Root?.Element("Containers")?.Elements("Container");
if (containers != null && containers.Any())
{
items.AddRange(ParseContainerElements(containers, workspaceId));
}
}
// Option 3: Try direct children of root element
if (!items.Any())
{
var directElements = doc.Root?.Elements().Where(e => e.Name != "NextMarker" && e.Name != "MaxResults");
if (directElements != null && directElements.Any())
{
items.AddRange(ParseGenericElements(directElements, workspaceId));
}
}
return items;
}
catch (Exception ex)
{
throw new InvalidOperationException($"Failed to parse OneLake items list response: {ex.Message}", ex);
}
}
public async Task<string> ListBlobsRawAsync(string workspaceId, string itemId, string? path = null, bool recursive = false, CancellationToken cancellationToken = default)
{
if (path is not null)
ValidatePathForTraversal(path, nameof(path));
var (normalizedWorkspaceId, normalizedItemId) = await GetNormalizedIdentifiersAsync(workspaceId, itemId, cancellationToken);
// If no path is specified, intelligently discover and search top-level folders
if (string.IsNullOrEmpty(path))
{
// For intelligent discovery, combine responses from multiple folders
var allResponses = new List<string>();
var topLevelFolders = new[] { "Files", "Tables" };
foreach (var folder in topLevelFolders)
{
try
{
var url = $"{OneLakeEndpoints.OneLakeDataPlaneBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}/{folder}";
url += $"?restype=container&comp=list";
if (recursive)
{
url += "&recursive=true";
}
var response = await SendDataPlaneRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
var content = await response.Content.ReadAsStringAsync(cancellationToken);
allResponses.Add($"<!-- Response for folder: {folder} -->\n{content}");
}
catch (Exception ex)
{
allResponses.Add($"<!-- Error accessing folder {folder}: {ex.Message} -->");
}
}
return string.Join("\n\n", allResponses);
}
// Use the OneLake blob endpoint to list files for specific path
var singleUrl = $"{OneLakeEndpoints.OneLakeDataPlaneBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}";
// If path is specified, check if it's a top-level folder (Tables, Files, etc.)
// or a sub-path within Files
var trimmedPath = path.TrimStart('/');
if (trimmedPath.StartsWith("Files/", StringComparison.OrdinalIgnoreCase))
{
// Path already includes Files prefix
singleUrl += $"/{trimmedPath}";
}
else if (trimmedPath.Equals("Files", StringComparison.OrdinalIgnoreCase))
{
// Explicitly requesting Files folder
singleUrl += "/Files";
}
else if (IsTopLevelFolder(trimmedPath))
{
// Top-level folder like Tables, Files, etc.
singleUrl += $"/{trimmedPath}";
}
else
{
// Assume it's a sub-path within Files for backward compatibility
singleUrl += $"/Files/{trimmedPath}";
}
singleUrl += $"?restype=container&comp=list";
if (recursive)
{
singleUrl += "&recursive=true";
}
var singleResponse = await SendDataPlaneRequestAsync(HttpMethod.Get, singleUrl, cancellationToken: cancellationToken);
return await singleResponse.Content.ReadAsStringAsync(cancellationToken);
}
public async Task<string> ListPathRawAsync(string workspaceId, string itemId, string? path = null, bool recursive = false, CancellationToken cancellationToken = default)
{
if (path is not null)
ValidatePathForTraversal(path, nameof(path));
var (normalizedWorkspaceId, normalizedItemId) = await GetNormalizedIdentifiersAsync(workspaceId, itemId, cancellationToken);
// If no path is specified, intelligently discover and search top-level folders
if (string.IsNullOrEmpty(path))
{
// For intelligent discovery, combine responses from multiple folders
var allResponses = new List<string>();
var topLevelFolders = new[] { "Files", "Tables" };
foreach (var folder in topLevelFolders)
{
try
{
var url = $"{OneLakeEndpoints.OneLakeDataPlaneDfsBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}/{folder}";
url += $"?resource=filesystem&recursive={recursive.ToString().ToLowerInvariant()}";
var response = await SendDataPlaneRequestAsync(HttpMethod.Get, url, cancellationToken: cancellationToken);
var content = await response.Content.ReadAsStringAsync(cancellationToken);
allResponses.Add($"/* Response for folder: {folder} */\n{content}");
}
catch (Exception ex)
{
allResponses.Add($"/* Error accessing folder {folder}: {ex.Message} */");
}
}
return string.Join("\n\n", allResponses);
}
// Use ADLS Gen2 filesystem API format instead of blob container format
var singleUrl = $"{OneLakeEndpoints.OneLakeDataPlaneDfsBaseUrl}/{normalizedWorkspaceId}/{normalizedItemId}";
// If path is specified, check if it's a top-level folder (Tables, Files, etc.)
// or a sub-path within Files
var trimmedPath = path.TrimStart('/');
if (trimmedPath.StartsWith("Files/", StringComparison.OrdinalIgnoreCase))
{
// Path already includes Files prefix
singleUrl += $"/{trimmedPath}";
}
else if (trimmedPath.Equals("Files", StringComparison.OrdinalIgnoreCase))
{
// Explicitly requesting Files folder
singleUrl += "/Files";
}