-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathdata_frames.rs
More file actions
1041 lines (872 loc) · 39.4 KB
/
data_frames.rs
File metadata and controls
1041 lines (872 loc) · 39.4 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
use std::path::{Path, PathBuf};
use crate::errors::OxenHttpError;
use crate::helpers::get_repo;
use crate::params::{DFOptsQuery, PageNumQuery, app_data, df_opts_query, path_param};
use actix_web::{HttpRequest, HttpResponse, web};
use liboxen::constants::{self, TABLE_NAME};
use liboxen::core::db::data_frames::df_db::with_df_db_manager;
use liboxen::core::db::data_frames::workspace_df_db::schema_without_oxen_cols;
use liboxen::error::OxenError;
use liboxen::model::{ParsedResource, Schema, Workspace};
use liboxen::opts::DFOpts;
use liboxen::repositories;
use liboxen::util::paginate;
use liboxen::view::data_frames::DataFramePayload;
use liboxen::view::entries::ResourceVersion;
use liboxen::view::entries::{PaginatedMetadataEntries, PaginatedMetadataEntriesResponse};
use liboxen::view::json_data_frame_view::WorkspaceJsonDataFrameViewResponse;
use liboxen::view::workspaces::RenameRequest;
use liboxen::view::{
JsonDataFrameViewResponse, JsonDataFrameViews, StatusMessage, StatusMessageDescription,
};
use actix_web::web::Bytes;
use futures_util::stream::Stream;
use std::io::{BufReader, Read};
use std::pin::Pin;
use std::task::{Context, Poll};
use tokio::sync::mpsc;
pub mod columns;
pub mod embeddings;
pub mod rows;
// Custom file stream that cleans up after completion
struct CleanupFileStream {
reader: BufReader<std::fs::File>,
temp_path: PathBuf,
buffer: [u8; 8192], // 8KB buffer
tx: Option<mpsc::Sender<()>>,
}
impl CleanupFileStream {
fn new(path: PathBuf) -> std::io::Result<Self> {
let file = std::fs::File::open(&path)?;
let reader = BufReader::new(file);
let (tx, _) = mpsc::channel(1);
Ok(Self {
reader,
temp_path: path,
buffer: [0; 8192],
tx: Some(tx),
})
}
}
impl Stream for CleanupFileStream {
type Item = Result<Bytes, std::io::Error>;
fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let this = &mut *self;
match this.reader.read(&mut this.buffer) {
Ok(0) => {
// EOF reached - clean up the file
if let Some(tx) = this.tx.take() {
let path = this.temp_path.clone();
tokio::spawn(async move {
log::debug!("removing temporary file {path:?}");
if let Err(e) = std::fs::remove_file(&path) {
log::error!("Failed to remove temporary file: {e:?}");
}
drop(tx); // Signal completion
});
}
Poll::Ready(None)
}
Ok(n) => {
let bytes = Bytes::copy_from_slice(&this.buffer[..n]);
Poll::Ready(Some(Ok(bytes)))
}
Err(e) => Poll::Ready(Some(Err(e))),
}
}
}
pub async fn get(
req: HttpRequest,
query: web::Query<DFOptsQuery>,
) -> Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req)?;
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let workspace_id = path_param(&req, "workspace_id")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
let file_path = PathBuf::from(path_param(&req, "path")?);
let mut opts = DFOpts::empty();
opts = df_opts_query::parse_opts(&query, &mut opts);
opts.path = Some(file_path.clone());
opts.page = Some(query.page.unwrap_or(constants::DEFAULT_PAGE_NUM));
opts.page_size = Some(query.page_size.unwrap_or(constants::DEFAULT_PAGE_SIZE));
let is_indexed = repositories::workspaces::data_frames::is_indexed(&workspace, &file_path)?;
if !is_indexed {
let commit = workspace.commit.clone();
let resource: ParsedResource = ParsedResource {
path: file_path.clone(),
version: PathBuf::from(commit.id.to_string()),
resource: file_path.clone(),
workspace: None,
commit: Some(commit.clone()),
branch: None,
};
let data_frame_slice =
repositories::data_frames::get_slice(&repo, &resource.clone(), &resource.path, &opts)
.await?;
let df = data_frame_slice.slice;
let count = if opts.has_filter_transform() {
data_frame_slice.total_entries
} else {
data_frame_slice.schemas.slice.size.height
};
let df_schema = if let Some(schema) =
repositories::data_frames::schemas::get_by_path(&repo, &commit, &file_path)?
{
schema
} else {
Schema::from_polars(df.schema())
};
let df_views =
JsonDataFrameViews::from_df_and_opts_unpaginated(df, df_schema, count, &opts).await;
let response = WorkspaceJsonDataFrameViewResponse {
status: StatusMessage::resource_found(),
data_frame: Some(df_views),
resource: None,
commit: None, // Not at a committed state
derived_resource: None,
is_indexed,
};
return Ok(HttpResponse::Ok().json(response));
}
log::debug!("querying data frame {file_path:?}");
log::debug!("opts: {opts:?}");
let count = repositories::workspaces::data_frames::count(&workspace, &file_path)?;
// Query the data frame
let df = repositories::workspaces::data_frames::query(&workspace, &file_path, &opts)?;
let Some(mut df_schema) =
repositories::data_frames::schemas::get_by_path(&repo, &workspace.commit, &file_path)?
else {
log::error!("Failed to get schema for data frame {file_path:?}");
return Err(OxenHttpError::NotFound);
};
let resource = ResourceVersion {
path: file_path.to_string_lossy().to_string(),
version: workspace.commit.id.to_string(),
};
let og_schema = if let Some(schema) =
repositories::data_frames::schemas::get_by_path(&repo, &workspace.commit, &resource.path)?
{
schema
} else {
Schema::from_polars(df.schema())
};
df_schema.update_metadata_from_schema(&og_schema);
let mut df_views =
JsonDataFrameViews::from_df_and_opts_unpaginated(df, df_schema, count, &opts).await;
repositories::workspaces::data_frames::columns::decorate_fields_with_column_diffs(
&workspace,
&file_path,
&mut df_views,
)?;
let new_schema = repositories::data_frames::schemas::get_staged_schema_with_staged_db_manager(
&workspace.workspace_repo,
&file_path,
)?;
repositories::workspaces::data_frames::columns::update_column_schemas(
new_schema,
&mut df_views,
)?;
let response = WorkspaceJsonDataFrameViewResponse {
status: StatusMessage::resource_found(),
data_frame: Some(df_views),
resource: Some(resource),
commit: None, // Not at a committed state
derived_resource: None,
is_indexed,
};
Ok(HttpResponse::Ok().json(response))
}
pub async fn get_schema(req: HttpRequest) -> Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req)?;
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let workspace_id = path_param(&req, "workspace_id")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
let file_path = PathBuf::from(path_param(&req, "path")?);
let is_indexed = repositories::workspaces::data_frames::is_indexed(&workspace, &file_path)?;
if !is_indexed {
repositories::workspaces::data_frames::index(&repo, &workspace, &file_path).await?;
}
let db_path = repositories::workspaces::data_frames::duckdb_path(&workspace, &file_path);
let schema = with_df_db_manager(&db_path, |manager| {
manager.with_conn(|conn| schema_without_oxen_cols(conn, TABLE_NAME))
})?;
Ok(HttpResponse::Ok().json(schema))
}
fn determine_extension<'a>(opts: &'a DFOpts, file_path: &'a Path) -> &'a str {
match &opts.output {
// If the user specified a format, we'll export to that format
Some(output) => output
.extension()
.unwrap_or_default()
.to_str()
.unwrap_or_default(),
None => file_path
.extension()
.unwrap_or_default()
.to_str()
.unwrap_or_default(),
}
}
// fn determine_content_type(extension: &str) -> &str {
// match extension {
// "parquet" => "application/octet-stream",
// "json" | "jsonl" | "ndjson" => "application/json",
// _ => "text/csv",
// }
// }
pub async fn download(
req: HttpRequest,
query: web::Query<DFOptsQuery>,
) -> Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req)?;
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let workspace_id = path_param(&req, "workspace_id")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
let file_path = PathBuf::from(path_param(&req, "path")?);
let Some(filename) = file_path.file_name().and_then(|n| n.to_str()) else {
log::error!(
"Unable to get filename from request param path: {}",
file_path.display()
);
return Err(OxenHttpError::BadRequest(
"Unable to parse filename from 'path' parameter".into(),
));
};
let opts = df_opts_from_query(&query, file_path.clone());
let is_indexed = repositories::workspaces::data_frames::is_indexed(&workspace, &file_path)?;
if !is_indexed {
let file_exists = file_exists_in_workspace_or_commit(&workspace, &file_path)?;
if !file_exists {
return Err(OxenHttpError::NotFound);
}
let response = df_not_indexed_response();
return Ok(HttpResponse::Ok().json(response));
}
log::debug!("exporting data frame {file_path:?}");
log::debug!("opts: {opts:?}");
// Create temporary file
let temp_dir = std::env::temp_dir();
let extension = determine_extension(&opts, &file_path);
let temp_file = temp_dir.join(format!("{}.{}", uuid::Uuid::new_v4(), extension));
// Export the data frame
match repositories::workspaces::data_frames::export(&workspace, &file_path, &opts, &temp_file) {
Ok(_) => (),
Err(e) => {
let error_str = format!("{e:?}");
log::error!("Error exporting data frame {file_path:?}: {error_str}");
let response = StatusMessageDescription::bad_request(error_str);
return Ok(HttpResponse::BadRequest().json(response));
}
};
// Read the entire file into memory
let contents = {
let mut file = std::fs::File::open(&temp_file)?;
let mut contents = Vec::new();
file.read_to_end(&mut contents)?;
contents
};
// Remove the temporary file
if let Err(e) = std::fs::remove_file(&temp_file) {
log::error!("Failed to remove temporary file: {e:?}");
}
// Create non-streaming response
Ok(HttpResponse::Ok()
// .append_header(("Content-Type", determine_content_type(extension)))
.append_header(("Content-Type", "text/csv"))
.append_header((
"Content-Disposition",
format!("attachment; filename=\"{filename}\""),
))
.body(contents))
}
fn df_opts_from_query(query: &web::Query<DFOptsQuery>, file_path: PathBuf) -> DFOpts {
let mut opts = DFOpts::empty();
opts = df_opts_query::parse_opts(query, &mut opts);
opts.path = Some(file_path);
opts.page = Some(query.page.unwrap_or(constants::DEFAULT_PAGE_NUM));
opts.page_size = Some(query.page_size.unwrap_or(constants::DEFAULT_PAGE_SIZE));
opts
}
/// Check if the file exists in the repository or the workspace.
/// If not, then it should be a genuine 404.
fn file_exists_in_workspace_or_commit(
workspace: &Workspace,
file_path: impl AsRef<Path>,
) -> Result<bool, OxenHttpError> {
let file_exists = {
(
// does the file exist in the base repository?
repositories::tree::get_file_by_path(
&workspace.base_repo,
&workspace.commit,
&file_path,
)?
.is_some()
) || (
// if not, does it exist in the workspace
repositories::workspaces::files::exists(workspace, &file_path)?
)
};
Ok(file_exists)
}
fn df_not_indexed_response() -> WorkspaceJsonDataFrameViewResponse {
WorkspaceJsonDataFrameViewResponse {
status: StatusMessage::resource_found(),
data_frame: None,
resource: None,
commit: None, // Not at a committed state
derived_resource: None,
is_indexed: false,
}
}
pub async fn download_streaming(
req: HttpRequest,
query: web::Query<DFOptsQuery>,
) -> Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req)?;
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let workspace_id = path_param(&req, "workspace_id")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
let file_path = PathBuf::from(path_param(&req, "path")?);
let Some(filename) = file_path.file_name().and_then(|n| n.to_str()) else {
log::error!(
"Unable to get filename from request param path: {}",
file_path.display()
);
return Err(OxenHttpError::BadRequest(
"Unable to parse filename from 'path' parameter".into(),
));
};
let opts = df_opts_from_query(&query, file_path.clone());
let is_indexed = repositories::workspaces::data_frames::is_indexed(&workspace, &file_path)?;
if !is_indexed {
let file_exists = file_exists_in_workspace_or_commit(&workspace, &file_path)?;
if !file_exists {
return Err(OxenHttpError::NotFound);
}
let response = df_not_indexed_response();
return Ok(HttpResponse::Ok().json(response));
}
log::debug!("exporting data frame {file_path:?}");
log::debug!("opts: {opts:?}");
// Create temporary file
let temp_dir = std::env::temp_dir();
let extension = determine_extension(&opts, &file_path);
let temp_file = temp_dir.join(format!("{}.{}", uuid::Uuid::new_v4(), extension));
// Export the data frame
match repositories::workspaces::data_frames::export(&workspace, &file_path, &opts, &temp_file) {
Ok(_) => (),
Err(e) => {
log::error!("Error exporting data frame {file_path:?}: {e:?}");
let error_str = format!("{e:?}");
let response = StatusMessageDescription::bad_request(error_str);
return Ok(HttpResponse::BadRequest().json(response));
}
};
let stream = CleanupFileStream::new(temp_file)?;
Ok(HttpResponse::Ok()
// .append_header(("Content-Type", determine_content_type(extension)))
.append_header(("Content-Type", "text/csv"))
.append_header((
"Content-Disposition",
format!("attachment; filename=\"{filename}\""),
))
.streaming(stream))
}
pub async fn get_by_branch(
req: HttpRequest,
query: web::Query<PageNumQuery>,
) -> actix_web::Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req).unwrap();
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let workspace_id = path_param(&req, "workspace_id")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let branch_name: &str = req.match_info().query("branch");
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
let page = query.page.unwrap_or(constants::DEFAULT_PAGE_NUM);
let page_size = query.page_size.unwrap_or(constants::DEFAULT_PAGE_SIZE);
// Staged dataframes must be on a branch.
let branch = repositories::branches::get_by_name(&repo, branch_name)?;
let commit = repositories::commits::get_by_id(&repo, &branch.commit_id)?
.ok_or_else(|| OxenError::resource_not_found(&branch.commit_id))?;
let entries = repositories::entries::list_tabular_files_in_repo(&repo, &commit)?;
log::debug!("got {} tabular entries", entries.len());
let mut editable_entries = vec![];
for entry in entries {
log::debug!("considering entry {entry:?}");
let path = PathBuf::from(&entry.filename);
if repositories::workspaces::data_frames::is_indexed(&workspace, &path)? {
editable_entries.push(entry);
} else {
log::debug!("not indexed {path:?}");
}
}
let (paginated_entries, pagination) = paginate(editable_entries, page, page_size);
Ok(HttpResponse::Ok().json(PaginatedMetadataEntriesResponse {
status: StatusMessage::resource_found(),
entries: PaginatedMetadataEntries {
entries: paginated_entries,
pagination,
},
}))
}
pub async fn diff(
req: HttpRequest,
query: web::Query<DFOptsQuery>,
) -> actix_web::Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req)?;
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let workspace_id = path_param(&req, "workspace_id")?;
let file_path = PathBuf::from(path_param(&req, "path")?);
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
let mut opts = DFOpts::empty();
opts = df_opts_query::parse_opts(&query, &mut opts);
opts.page = Some(query.page.unwrap_or(constants::DEFAULT_PAGE_NUM));
opts.page_size = Some(query.page_size.unwrap_or(constants::DEFAULT_PAGE_SIZE));
let df = repositories::workspaces::data_frames::query(&workspace, &file_path, &opts)?;
let diff_df = repositories::workspaces::data_frames::diff(&workspace, &file_path)?;
let mut df_schema =
repositories::workspaces::data_frames::schemas::get_by_path(&workspace, &file_path)?;
let resource = ResourceVersion {
path: file_path.to_string_lossy().to_string(),
version: workspace.commit.id.to_string(),
};
let og_schema = if let Some(schema) =
repositories::data_frames::schemas::get_by_path(&repo, &workspace.commit, resource.path)?
{
schema
} else {
Schema::from_polars(df.schema())
};
df_schema.update_metadata_from_schema(&og_schema);
let mut df_views = JsonDataFrameViews::from_df_and_opts(diff_df, df_schema, &opts).await;
repositories::workspaces::data_frames::columns::decorate_fields_with_column_diffs(
&workspace,
&file_path,
&mut df_views,
)?;
let resource = ResourceVersion {
path: file_path.to_string_lossy().to_string(),
version: workspace.commit.id.to_string(),
};
let resource = JsonDataFrameViewResponse {
data_frame: df_views,
status: StatusMessage::resource_found(),
resource: Some(resource),
commit: None,
derived_resource: None,
};
Ok(HttpResponse::Ok().json(resource))
}
/// Index a data frame into DuckDB for querying
pub async fn put(req: HttpRequest, body: String) -> Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req)?;
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let workspace_id = path_param(&req, "workspace_id")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let file_path = PathBuf::from(path_param(&req, "path")?);
log::debug!("workspace {workspace_id} data frame put {file_path:?}");
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
let data: DataFramePayload = serde_json::from_str(&body)?;
log::debug!("workspace {workspace_id} data frame put {data:?}");
let to_index = data.is_indexed;
let is_indexed = repositories::workspaces::data_frames::is_indexed(&workspace, &file_path)?;
if !is_indexed && to_index {
repositories::workspaces::data_frames::index(&repo, &workspace, &file_path).await?;
} else if is_indexed && !to_index {
repositories::workspaces::data_frames::unindex(&workspace, &file_path)?;
}
Ok(HttpResponse::Ok().json(StatusMessage::resource_updated()))
}
pub async fn delete(req: HttpRequest) -> Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req)?;
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let workspace_id = path_param(&req, "workspace_id")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let file_path = PathBuf::from(path_param(&req, "path")?);
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
repositories::workspaces::data_frames::restore(&repo, &workspace, file_path).await?;
Ok(HttpResponse::Ok().json(StatusMessage::resource_deleted()))
}
pub async fn rename(req: HttpRequest, body: String) -> Result<HttpResponse, OxenHttpError> {
let app_data = app_data(&req)?;
let namespace = path_param(&req, "namespace")?;
let repo_name = path_param(&req, "repo_name")?;
let workspace_id = path_param(&req, "workspace_id")?;
let repo = get_repo(&app_data.path, namespace, repo_name)?;
let path = PathBuf::from(path_param(&req, "path")?);
// Attempt to parse the body
let body: RenameRequest = serde_json::from_str(&body)?; // Use the Json wrapper to get the inner value
// Check if new_path is valid
if body.new_path.is_empty() {
return Err(OxenHttpError::BadRequest("new_path cannot be empty".into()));
}
let new_path = PathBuf::from(body.new_path);
let Some(workspace) = repositories::workspaces::get(&repo, &workspace_id)? else {
return Ok(HttpResponse::NotFound()
.json(StatusMessageDescription::workspace_not_found(workspace_id)));
};
if repositories::entries::get_file(&repo, &workspace.commit, &new_path)?.is_some() {
return Err(OxenHttpError::BadRequest("new_path already exists".into()));
}
repositories::workspaces::data_frames::rename(&workspace, &path, &new_path).await?;
Ok(HttpResponse::Ok().json(StatusMessage::resource_updated()))
}
#[cfg(test)]
mod tests {
use crate::app_data::OxenAppData;
use crate::controllers;
use crate::test;
use actix_web::{App, web};
use liboxen::error::OxenError;
use liboxen::repositories;
use liboxen::util;
use liboxen::view::json_data_frame_view::WorkspaceJsonDataFrameViewResponse;
/// CSV committed, workspace created, dataframe indexed.
/// Expected: 200 with `text/csv` body containing the data.
#[actix_web::test]
async fn test_download_indexed_data_frame_returns_csv_content() -> Result<(), OxenError> {
liboxen::test::init_test_env();
let sync_dir = test::get_sync_dir()?;
let namespace = "Testing-Namespace";
let repo_name = "Testing-Name";
let repo = test::create_local_repo(&sync_dir, namespace, repo_name)?;
// Create a CSV file and commit
let csv_dir = repo.path.join("data");
util::fs::create_dir_all(&csv_dir)?;
let csv_path = csv_dir.join("test.csv");
util::fs::write_to_path(&csv_path, "col_a,col_b\n1,2\n3,4\n")?;
repositories::add(&repo, &csv_path).await?;
let commit = repositories::commit(&repo, "Add CSV")?;
// Create a workspace and index the data frame
let workspace_id = uuid::Uuid::new_v4().to_string();
let workspace = repositories::workspaces::create(&repo, &commit, &workspace_id, false)?;
let file_path = std::path::Path::new("data/test.csv");
repositories::workspaces::data_frames::index(&repo, &workspace, file_path).await?;
// Request download for the indexed file
let uri = format!(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download/{}",
file_path.display()
);
let app = actix_web::test::init_service(
App::new()
.app_data(OxenAppData::new(sync_dir.clone()))
.route(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download/{path:.*}",
web::get().to(controllers::workspaces::data_frames::download),
),
)
.await;
let req = actix_web::test::TestRequest::get().uri(&uri).to_request();
let resp = actix_web::test::call_service(&app, req).await;
assert_eq!(resp.status(), actix_web::http::StatusCode::OK);
// Verify it returned CSV content, not JSON
let content_type = resp
.headers()
.get("Content-Type")
.unwrap()
.to_str()
.unwrap();
assert_eq!(content_type, "text/csv");
let bytes = actix_http::body::to_bytes(resp.into_body()).await.unwrap();
let body = String::from_utf8(bytes.to_vec()).unwrap();
assert!(body.contains("col_a"));
assert!(body.contains("col_b"));
// cleanup
test::cleanup_sync_dir(&sync_dir)?;
Ok(())
}
/// File NOT in base commit, only staged in workspace via `files::add`.
/// Expected: 200 JSON with `is_indexed: false`, `data_frame: None`.
#[actix_web::test]
async fn test_download_unindexed_workspace_only_file_returns_200() -> Result<(), OxenError> {
liboxen::test::init_test_env();
let sync_dir = test::get_sync_dir()?;
let namespace = "Testing-Namespace";
let repo_name = "Testing-Name";
let repo = test::create_local_repo(&sync_dir, namespace, repo_name)?;
// Create an initial file and commit so we have a valid commit for the workspace
let readme = repo.path.join("README.md");
util::fs::write_to_path(&readme, "# Test")?;
repositories::add(&repo, &readme).await?;
let commit = repositories::commit(&repo, "Initial commit")?;
// Create workspace, then add a NEW CSV that doesn't exist in the base commit
let workspace_id = uuid::Uuid::new_v4().to_string();
let workspace = repositories::workspaces::create(&repo, &commit, &workspace_id, false)?;
// Write the new CSV into the workspace directory and stage it
let workspace_csv_dir = workspace.dir().join("data");
util::fs::create_dir_all(&workspace_csv_dir)?;
let workspace_csv_path = workspace_csv_dir.join("new.csv");
util::fs::write_to_path(&workspace_csv_path, "x,y\n10,20\n")?;
repositories::workspaces::files::add(&workspace, &workspace_csv_path).await?;
// Request download for the workspace-only file
let file_path = "data/new.csv";
let uri = format!(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download/{file_path}"
);
let app = actix_web::test::init_service(
App::new()
.app_data(OxenAppData::new(sync_dir.clone()))
.route(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download/{path:.*}",
web::get().to(controllers::workspaces::data_frames::download),
),
)
.await;
let req = actix_web::test::TestRequest::get().uri(&uri).to_request();
let resp = actix_web::test::call_service(&app, req).await;
assert_eq!(resp.status(), actix_web::http::StatusCode::OK);
// Parse the response body and verify is_indexed is false
let bytes = actix_http::body::to_bytes(resp.into_body()).await.unwrap();
let response: WorkspaceJsonDataFrameViewResponse = serde_json::from_slice(&bytes)?;
assert!(!response.is_indexed);
assert!(response.data_frame.is_none());
// cleanup
test::cleanup_sync_dir(&sync_dir)?;
Ok(())
}
/// File doesn't exist in base commit or workspace.
/// Expected: 404.
#[actix_web::test]
async fn test_download_nonexistent_path_returns_404() -> Result<(), OxenError> {
liboxen::test::init_test_env();
let sync_dir = test::get_sync_dir()?;
let namespace = "Testing-Namespace";
let repo_name = "Testing-Name";
let repo = test::create_local_repo(&sync_dir, namespace, repo_name)?;
// Create a CSV file and commit so we have a valid repo
let csv_dir = repo.path.join("data");
util::fs::create_dir_all(&csv_dir)?;
let csv_path = csv_dir.join("test.csv");
util::fs::write_to_path(&csv_path, "col_a,col_b\n1,2\n3,4\n")?;
repositories::add(&repo, &csv_path).await?;
let commit = repositories::commit(&repo, "Add CSV")?;
// Create a workspace
let workspace_id = uuid::Uuid::new_v4().to_string();
repositories::workspaces::create(&repo, &commit, &workspace_id, false)?;
// Request download for a file that does not exist
let nonexistent_path = "data/this_does_not_exist.csv";
let uri = format!(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download/{nonexistent_path}"
);
let app = actix_web::test::init_service(
App::new()
.app_data(OxenAppData::new(sync_dir.clone()))
.route(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download/{path:.*}",
web::get().to(controllers::workspaces::data_frames::download),
),
)
.await;
let req = actix_web::test::TestRequest::get().uri(&uri).to_request();
let resp = actix_web::test::call_service(&app, req).await;
assert_eq!(resp.status(), actix_web::http::StatusCode::NOT_FOUND);
// cleanup
test::cleanup_sync_dir(&sync_dir)?;
Ok(())
}
/// CSV committed, workspace created, NOT indexed.
/// Expected: 200 JSON with `is_indexed: false`, `data_frame: None`.
#[actix_web::test]
async fn test_download_existing_unindexed_returns_200_with_is_indexed_false()
-> Result<(), OxenError> {
liboxen::test::init_test_env();
let sync_dir = test::get_sync_dir()?;
let namespace = "Testing-Namespace";
let repo_name = "Testing-Name";
let repo = test::create_local_repo(&sync_dir, namespace, repo_name)?;
// Create a CSV file and commit
let csv_dir = repo.path.join("data");
util::fs::create_dir_all(&csv_dir)?;
let csv_path = csv_dir.join("test.csv");
util::fs::write_to_path(&csv_path, "col_a,col_b\n1,2\n3,4\n")?;
repositories::add(&repo, &csv_path).await?;
let commit = repositories::commit(&repo, "Add CSV")?;
// Create a workspace but do NOT index the data frame
let workspace_id = uuid::Uuid::new_v4().to_string();
repositories::workspaces::create(&repo, &commit, &workspace_id, false)?;
// Request download for the existing-but-unindexed file
let file_path = "data/test.csv";
let uri = format!(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download/{file_path}"
);
let app = actix_web::test::init_service(
App::new()
.app_data(OxenAppData::new(sync_dir.clone()))
.route(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download/{path:.*}",
web::get().to(controllers::workspaces::data_frames::download),
),
)
.await;
let req = actix_web::test::TestRequest::get().uri(&uri).to_request();
let resp = actix_web::test::call_service(&app, req).await;
assert_eq!(resp.status(), actix_web::http::StatusCode::OK);
// Parse the response body and verify is_indexed is false
let bytes = actix_http::body::to_bytes(resp.into_body()).await.unwrap();
let response: WorkspaceJsonDataFrameViewResponse = serde_json::from_slice(&bytes)?;
assert!(!response.is_indexed);
assert!(response.data_frame.is_none());
// cleanup
test::cleanup_sync_dir(&sync_dir)?;
Ok(())
}
/// CSV committed, workspace created, file not staged in workspace.
/// Expected: 200 JSON with `is_indexed: false`, `data_frame: None`.
#[actix_web::test]
async fn test_download_streaming_unindexed_committed_file_returns_200() -> Result<(), OxenError>
{
liboxen::test::init_test_env();
let sync_dir = test::get_sync_dir()?;
let namespace = "Testing-Namespace";
let repo_name = "Testing-Name";
let repo = test::create_local_repo(&sync_dir, namespace, repo_name)?;
let csv_dir = repo.path.join("data");
util::fs::create_dir_all(&csv_dir)?;
let csv_path = csv_dir.join("test.csv");
util::fs::write_to_path(&csv_path, "col_a,col_b\n1,2\n3,4\n")?;
repositories::add(&repo, &csv_path).await?;
let commit = repositories::commit(&repo, "Add CSV")?;
let workspace_id = uuid::Uuid::new_v4().to_string();
repositories::workspaces::create(&repo, &commit, &workspace_id, false)?;
let file_path = "data/test.csv";
let uri = format!(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download_streaming/{file_path}"
);
let app = actix_web::test::init_service(
App::new()
.app_data(OxenAppData::new(sync_dir.clone()))
.route(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download_streaming/{path:.*}",
web::get().to(controllers::workspaces::data_frames::download_streaming),
),
)
.await;
let req = actix_web::test::TestRequest::get().uri(&uri).to_request();
let resp = actix_web::test::call_service(&app, req).await;
assert_eq!(resp.status(), actix_web::http::StatusCode::OK);
let bytes = actix_http::body::to_bytes(resp.into_body()).await.unwrap();
let response: WorkspaceJsonDataFrameViewResponse = serde_json::from_slice(&bytes)?;
assert!(!response.is_indexed);
assert!(response.data_frame.is_none());
test::cleanup_sync_dir(&sync_dir)?;
Ok(())
}
/// File NOT in base commit, only staged in workspace via `files::add`.
/// Expected: 200 JSON with `is_indexed: false`, `data_frame: None`.
#[actix_web::test]
async fn test_download_streaming_unindexed_workspace_only_file_returns_200()
-> Result<(), OxenError> {
liboxen::test::init_test_env();
let sync_dir = test::get_sync_dir()?;
let namespace = "Testing-Namespace";
let repo_name = "Testing-Name";
let repo = test::create_local_repo(&sync_dir, namespace, repo_name)?;
let readme = repo.path.join("README.md");
util::fs::write_to_path(&readme, "# Test")?;
repositories::add(&repo, &readme).await?;
let commit = repositories::commit(&repo, "Initial commit")?;
let workspace_id = uuid::Uuid::new_v4().to_string();
let workspace = repositories::workspaces::create(&repo, &commit, &workspace_id, false)?;
let workspace_csv_dir = workspace.dir().join("data");
util::fs::create_dir_all(&workspace_csv_dir)?;
let workspace_csv_path = workspace_csv_dir.join("new.csv");
util::fs::write_to_path(&workspace_csv_path, "x,y\n10,20\n")?;
repositories::workspaces::files::add(&workspace, &workspace_csv_path).await?;
let file_path = "data/new.csv";
let uri = format!(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download_streaming/{file_path}"
);
let app = actix_web::test::init_service(
App::new()
.app_data(OxenAppData::new(sync_dir.clone()))
.route(
"/oxen/{namespace}/{repo_name}/workspaces/{workspace_id}/data_frames/download_streaming/{path:.*}",
web::get().to(controllers::workspaces::data_frames::download_streaming),
),
)
.await;
let req = actix_web::test::TestRequest::get().uri(&uri).to_request();
let resp = actix_web::test::call_service(&app, req).await;
assert_eq!(resp.status(), actix_web::http::StatusCode::OK);
let bytes = actix_http::body::to_bytes(resp.into_body()).await.unwrap();
let response: WorkspaceJsonDataFrameViewResponse = serde_json::from_slice(&bytes)?;
assert!(!response.is_indexed);
assert!(response.data_frame.is_none());
test::cleanup_sync_dir(&sync_dir)?;
Ok(())
}
/// File doesn't exist in base commit or workspace.
/// Expected: 404.