Spaces:
Sleeping

File size: 6,647 Bytes
4b88607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
af7255e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b88607
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
library(plumber)
library(jsonlite)
library(readr)
library(dplyr)

# Source helper functions
source("helpers.R")

# Add CORS headers for web usage
#* @filter cors
cors <- function(req, res) {
  res$setHeader("Access-Control-Allow-Origin", "*")
  res$setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS")
  res$setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,X-API-Key")
  
  if (req$REQUEST_METHOD == "OPTIONS") {
    res$status <- 200
    return(list())
  } else {
    forward()
  }
}

# API Key authentication (optional)
#* @filter auth
auth <- function(req, res) {
  api_key <- Sys.getenv("API_KEY")
  if (nchar(api_key) > 0) {
    provided_key <- req$HTTP_X_API_KEY
    if (is.null(provided_key) || provided_key != api_key) {
      res$status <- 401
      return(list(error = "Unauthorized: Invalid or missing API key"))
    }
  }
  forward()
}

# Request logging
#* @filter logger
function(req) {
  cat(paste0(
    "[", Sys.time(), "] ",
    req$REQUEST_METHOD, " ",
    req$PATH_INFO, " - ",
    req$REMOTE_ADDR, "\n"
  ))
  forward()
}

#* Health check endpoint
#* @get /health
function() {
  list(
    status = "ok",
    service = "equil2-api",
    time = as.character(Sys.time()),
    uptime = as.numeric(proc.time()[3])
  )
}

#* Version information
#* @get /version
function() {
  list(
    service = "equil2-api",
    version = "1.0.0",
    r_version = R.version$version.string,
    pkg_equil2 = as.character(utils::packageVersion("equil2")),
    pkg_plumber = as.character(utils::packageVersion("plumber")),
    license = "GPL-3 (equil2 package)"
  )
}

#* Compute urinary supersaturation from JSON
#* @post /equil2/compute
#* @serializer json
function(req, res) {
  tryCatch({
    # Parse JSON body
    body <- jsonlite::fromJSON(req$postBody, simplifyVector = TRUE)
    
    if (!is.null(body$records)) {
      # Process records array
      df_in <- normalize_records_to_df(body$records)
    } else if (!is.null(body$csv)) {
      # Process inline CSV string
      df_in <- readr::read_csv(I(body$csv), show_col_types = FALSE)
    } else {
      res$status <- 400
      return(list(error = "Provide either 'records' array or 'csv' string"))
    }
    
    # Convert units and validate
    df_conv <- convert_and_validate(df_in)
    
    # Run EQUIL2 computation
    result <- run_equil2_dataframe(df_conv)
    
    return(result)
    
  }, error = function(e) {
    res$status <- 400
    list(error = paste("Computation failed:", conditionMessage(e)))
  })
}

#* Compute urinary supersaturation from CSV file upload
#* @post /equil2/compute_csv
#* @parser multi
#* @serializer json
function(req, res) {
  tryCatch({
    # Check for uploaded file
    file <- req$files[["file"]]
    if (is.null(file) || is.null(file$datapath)) {
      res$status <- 400
      return(list(error = "Missing file upload. Use 'file' as the form field name."))
    }
    
    # Read CSV file
    df_in <- readr::read_csv(file$datapath, show_col_types = FALSE)
    
    # Convert units and validate
    df_conv <- convert_and_validate(df_in)
    
    # Run EQUIL2 computation
    result <- run_equil2_dataframe(df_conv)
    
    return(result)
    
  }, error = function(e) {
    res$status <- 400
    list(error = paste("CSV processing failed:", conditionMessage(e)))
  })
}

#* Get example input format
#* @get /equil2/example
function() {
  list(
    description = "Example input format for EQUIL2 computation",
    units = list(
      concentrations = "mmol/L or mg/L (will be converted)",
      pH = "logarithmic units (4-8.5 range expected)"
    ),
    example_record = list(
      Na_mmolL = 45,
      K_mmolL = 55,
      Ca_mgL = 150,
      Mg_mgL = 150,
      NH4_mmolL = 10,
      Cl_mmolL = 75,
      PO4_mgL = 1000,
      SO4_mmolL = 20,
      Ox_mgL = 100,
      Citr_mgL = 4000,
      Urate_mgL = 500,
      pH = 5.5
    ),
    alternative_units = list(
      note = "You can also provide *_mmolL instead of *_mgL for any component",
      example = "Ca_mmolL instead of Ca_mgL"
    )
  )
}

#* API limits and capabilities
#* @get /equil2/limits
function() {
  list(
    max_records_per_request = 1000,
    timeout_seconds = 120,
    supported_formats = c("JSON", "CSV"),
    required_fields = c("Na_mmolL", "K_mmolL", "NH4_mmolL", "Cl_mmolL", "SO4_mmolL", "pH"),
    optional_fields = c("Ca_mgL", "Mg_mgL", "PO4_mgL", "Ox_mgL", "Citr_mgL", "Urate_mgL"),
    output_fields = c("SS_CaOx", "SS_Brushite", "SS_HAp", "SS_UricAcid", "DG_CaOx", "DG_Brushite", "DG_HAp", "DG_UricAcid")
  )
}

#* Debug endpoint - Test input structure
#* @get /debug/test_input
function() {
  # Simula esattamente quello che fa l'API
  test_df <- tibble::tibble(
    Na_mmolL = 50,
    K_mmolL = 40,
    Ca_mmolL = 3.74,
    Mg_mmolL = 0.01,
    NH4_mmolL = 10,
    Cl_mmolL = 80,
    PO4_mmolL = 4.74,
    SO4_mmolL = 15,
    Ox_mmolL = 0.28,
    Citr_mmolL = 0.01,
    Urate_mmolL = 0.01,
    pH = 6.0
  )
  
  # Test estrazione con [[i]]
  i <- 1
  test_value <- test_df$Na_mmolL[[i]]
  
  # Crea input per equil2
  urine_input <- list(
    Na = as.numeric(test_df$Na_mmolL[[i]]),
    K = as.numeric(test_df$K_mmolL[[i]]),
    Ca = as.numeric(test_df$Ca_mmolL[[i]]),
    Mg = as.numeric(test_df$Mg_mmolL[[i]]),
    NH4 = as.numeric(test_df$NH4_mmolL[[i]]),
    Cl = as.numeric(test_df$Cl_mmolL[[i]]),
    PO4 = as.numeric(test_df$PO4_mmolL[[i]]),
    SO4 = as.numeric(test_df$SO4_mmolL[[i]]),
    C2O4 = as.numeric(test_df$Ox_mmolL[[i]]),
    Citrate = as.numeric(test_df$Citr_mmolL[[i]]),
    Uric = as.numeric(test_df$Urate_mmolL[[i]]),
    pH = as.numeric(test_df$pH[[i]])
  )
  
  # Verifica tipi
  types_info <- lapply(urine_input, function(x) {
    list(
      class = class(x),
      type = typeof(x),
      length = length(x),
      value = x
    )
  })
  
  # Prova chiamata equil2
  equil_result <- tryCatch({
    res <- equil2::equil2(urine_input)
    list(
      status = "success",
      SS_CaOx = as.numeric(res$RSS["CaOx"]),
      message = "equil2 call succeeded"
    )
  }, error = function(e) {
    list(
      status = "error",
      message = conditionMessage(e)
    )
  })
  
  return(list(
    test_extraction = list(
      value = test_value,
      class = class(test_value),
      length = length(test_value)
    ),
    input_types = types_info,
    equil2_result = equil_result,
    helpers_version = "2.0",
    timestamp = as.character(Sys.time())
  ))
}