Commit 0633245fa969d905078449341b616f068f70aac6

Stephen Moloney 2016-02-07T18:41:33

Change httpotion options to a map type. Also general cleanup.

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
diff --git a/lib/client.ex b/lib/client.ex
index ab66c69..3a215fa 100644
--- a/lib/client.ex
+++ b/lib/client.ex
@@ -2,6 +2,17 @@ defmodule ExOvh.Client do
   alias LoggingUtils
   alias ExOvh.Defaults
 
+  # <<TODO>> Reconsider is here the best place to declare the types
+  @type method_t :: atom()
+  @type path_t :: String.t
+  @type params_t :: map() | :nil
+  @type options_t :: map() | :nil
+
+  @type raw_query_t :: { method_t, path_t, params_t }
+  @type query_t :: { method_t, path_t, options_t }
+
+  @type response_t :: %{ body: map(), headers: map(), status_code: integer() }
+
   defmacro __using__(opts) do
     quote bind_quoted: [opts: opts] do
       @otp_app opts[:otp_app] || :ex_ovh
@@ -15,20 +26,22 @@ defmodule ExOvh.Client do
 
 
       def start_link(opts \\ []) do
-        LoggingUtils.log_mod_func_line(__ENV__, :debug)
         ExOvh.Supervisor.start_link(__MODULE__, config(), opts)
       end
 
 
-      def ovh_request(method, uri, params, signed \\ :true) do
-        LoggingUtils.log_mod_func_line(__ENV__, :debug)
-        ExOvh.Ovh.Request.request(__MODULE__, method, uri, params, signed)
+      def ovh_request({method, uri, params} = query) do
+        ExOvh.Ovh.Request.request(__MODULE__, query)
+      end
+
+
+      def ovh_request({method, uri, params} = query) do
+        ExOvh.Ovh.Request.request(__MODULE__, query)
       end
 
 
-      def ovh_prep_request(method, uri, params, signed \\ :true) do
-        LoggingUtils.log_mod_func_line(__ENV__, :debug)
-        ExOvh.Ovh.Auth.prep_request(__MODULE__, method, uri, params, signed)
+      def ovh_prep_request({method, uri, params} = query) do
+        ExOvh.Ovh.Auth.prep_request(__MODULE__, query)
       end
 
 
@@ -46,14 +59,16 @@ defmodule ExOvh.Client do
   Makes a request to the ovh api.
   Returns a map `%{ body: <body>, headers: [<headers>], status_code: <code>}`
   """
-  @callback ovh_request(method :: atom, uri :: string, params :: map, signed :: boolean) :: map
+  @callback ovh_request(query :: raw_query_t)
+                        :: {:ok, response_t} | {:error, response_t}
 
 
   @doc ~s"""
   Prepares all elements necessary prior to making a request to the ovh api.
   Returns a tuple `{method, uri, options}`
   """
-  @callback ovh_prep_request(method :: atom, uri :: String.t, params :: map, signed :: boolean) :: tuple
+  @callback ovh_prep_request(query :: raw_query_t)
+                             :: query_t
 
 
 end
diff --git a/lib/ex_ovh.ex b/lib/ex_ovh.ex
index 30d4277..da33c39 100644
--- a/lib/ex_ovh.ex
+++ b/lib/ex_ovh.ex
@@ -1,7 +1,6 @@
 defmodule ExOvh do
   use ExOvh.Client, otp_app: :ex_ovh
 
-
   # <<TODO>> Remove application later so that ExOvh is started
   # <<TODO>> within a supervision tree on demand
   use Application
diff --git a/lib/hubic/auth.ex b/lib/hubic/auth.ex
index 306e944..5774fef 100644
--- a/lib/hubic/auth.ex
+++ b/lib/hubic/auth.ex
@@ -1,7 +1,8 @@
 defmodule ExOvh.Hubic.Auth do
   @moduledoc "Gets the access and refresh token for access the hubic api"
+
   alias ExOvh.Hubic.Defaults
-  alias ExOvh.Hubic.TokenCache, as: Cache
+  alias ExOvh.Hubic.Cache
   @timeout 20_000
 
 
@@ -9,48 +10,32 @@ defmodule ExOvh.Hubic.Auth do
   # Public
   ###################
   
-  @spec prep_request(method :: atom, uri :: String.t, params :: map) :: tuple
-  def prep_request(method, uri, params), do: prep_request(ExOvh, method, uri, params)
-
+  @spec prep_request(query :: ExOvh.Client.raw_query_t)
+                     :: ExOvh.Client.query_t
+  def prep_request({method, uri, params} = query), do: prep_request(ExOvh, query)
 
-  @spec prep_request(client :: atom, method :: atom, uri :: String.t, params :: map) :: tuple
-  def prep_request(client, method, uri, params)
-  def prep_request(client, method, uri, params) when method in [:get, :delete] do
-    config = config(client)
-    |> LoggingUtils.log_return(:debug)
-    uri = uri(config, uri)
-    |> LoggingUtils.log_return(:debug)
-    if params !== :nil and params !== "", do: uri = uri <> URI.encode_query(params)
-    options = [ headers: headers(method), timeout: @timeout ]
-    {method, uri, options}
-  end
 
-  def prep_request(client, method, uri, params) when method in [:post, :put] do
-    config = config(client)
-    uri = uri(config, uri)
-    if params !== "" and params !== :nil, do: params = Poison.encode!(params)
-    options = [ body: params, headers: headers(method), timeout: @timeout ]
-    {method, uri, options}
-  end
+  @spec prep_request(client :: atom, query :: ExOvh.Client.raw_query_t)
+                    :: ExOvh.Client.query_t
+  def prep_request(client, query)
 
-  def prep_request(client, method, uri, params) when method in [:get, :delete] do
+  def prep_request(client, {method, uri, params} = query) when method in [:get, :delete] do
     config = config(client)
     uri = uri(config, uri)
     if params !== :nil and params !== "", do: uri = uri <> URI.encode_query(params)
-    options = [ headers: headers(method), timeout: @timeout ]
+    options = %{ headers: headers(method), timeout: @timeout }
     {method, uri, options}
   end
 
-  def prep_request(client, method, uri, params) when method in [:post, :put] do
+  def prep_request(client, {method, uri, params} = query) when method in [:post, :put] do
     config = config(client)
     uri = uri(config, uri)
-    if params !== "" and params !== :nil and method in [:post, :put], do: params = Poison.encode!(params)
-    options = [ body: params, headers: headers(method), timeout: @timeout ]
+    if params !== "" and params !== :nil, do: params = Poison.encode!(params)
+    options = %{ body: params, headers: headers(method), timeout: @timeout }
     {method, uri, options}
   end
 
 
-
   @doc """
   - It is necessary to perform this request every time the access token expires.
   - The refresh token needs to be available to perform this request.
@@ -68,23 +53,18 @@ defmodule ExOvh.Hubic.Auth do
     auth_credentials_base64 = Base.encode64(auth_credentials)
     req_body = "refresh_token=" <> refresh_token <>
                 "&grant_type=refresh_token"
-    headers = [
+    headers = %{
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": "Basic " <> auth_credentials_base64
-              ]
-    req_options = [
-                  body: req_body,
-                  headers: headers,
-                  timeout: @timeout
-                  ]
-    resp = HTTPotion.request(:post, hubic_token_uri(config), req_options)
+              }
+    options = %{ body: req_body, headers: headers, timeout: @timeout }
+    resp = HTTPotion.request(:post, hubic_token_uri(config), options)
     resp =
     %{
       body: resp.body |> Poison.decode!(),
-      headers: resp.headers |> Enum.into(%{}),
+      headers: resp.headers,
       status_code: resp.status_code
     }
-    |> LoggingUtils.log_return(:debug)
     if Map.has_key?(resp, "error") do
       error = Map.get(resp, "error") <> " :: " <> Map.get(resp, "error_description")
       raise error
@@ -97,12 +77,9 @@ defmodule ExOvh.Hubic.Auth do
   # Private
   ###################
 
-  defp default_headers(), do: ["Authorization": "Bearer " <> Cache.get_token()]
+  defp default_headers(), do: %{ "Authorization": "Bearer " <> Cache.get_token() }
   defp headers(method) when method in [:post, :put] do
-    default_headers() ++
-    [
-      "Content-Type": "application/x-www-form-urlencoded"
-    ]
+    Map.merge(default_headers(), %{ "Content-Type": "application/x-www-form-urlencoded" })
   end
   defp headers(method) when method in [:get, :delete], do: default_headers()
 
diff --git a/lib/hubic/cache.ex b/lib/hubic/cache.ex
new file mode 100644
index 0000000..32dca4b
--- /dev/null
+++ b/lib/hubic/cache.ex
@@ -0,0 +1,194 @@
+defmodule ExOvh.Hubic.Cache do
+  @moduledoc ~s"""
+  Caches the access_token and provides a simple get_token() api to other modules through one function get_token()
+  Caches the hubic config map.
+
+  Maintains the access token so that:
+  - State is maintained in gen_server state but gen_server could be a bottleneck so it is also copied to a public ets table.
+  - So state is also stored in an ets table and is quickly and globally retrievable.
+  - State in :ets and :gen_server should be synchronised.
+  - It is automatically refreshed in the background when it expires
+  - If the gen_server crashes, it will attempt to re-establish the access token
+  - The refresh token by attempting the following:
+    - 1. Firstly, try to recuperate the refresh_token from a dets entry.
+    - 2. Secondly, by checking for the refresh_token in the config secret file.
+  - If both of the above methods fail, then ultimately the gen_server will crash and the user
+    will have to retrieve another refresh_token using the `mix hubic` task
+
+  tokens is a map with the following structure:
+  - `%{
+       :lock => :true,
+       "access_token" => "access_token",
+       "expires_in" => 21600,
+       "refresh_token" => "refresh_token",
+       "token_type" => "Bearer"
+    }`
+  """
+  use GenServer
+  alias ExOvh.Hubic.Auth
+  @get_token_retries 20
+  @get_token_sleep_interval 300
+
+
+  #####################
+  # Public
+  #####################
+
+
+  @doc "Starts the genserver"
+  def start_link({client, config, opts}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    GenServer.start_link(__MODULE__, {client, config, opts}, [name: gen_server_name(client)])
+  end
+
+
+  @doc "Gets the access_token from the :ets table"
+  @spec get_token() :: String.t
+  def get_token(), do: get_token(ExOvh, 0)
+
+  @doc "Gets the access_token from the :ets table"
+  @spec get_token(client :: atom) :: String.t
+  def get_token(client), do: get_token(client, 0)
+
+  @doc "Retrieves the hubic config map"
+  def get_config(client) do
+    GenServer.call(gen_server_name(client), :get_config)
+  end
+
+
+  #####################
+  # Genserver Callbacks
+  #####################
+
+  # trap exits so that terminate callback is invoked
+  # the :lock key is to allow for locking during the brief moment that the access token is being refreshed
+  def init({client, config, _opts}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    :erlang.process_flag(:trap_exit, :true)
+    create_ets_table(client)
+    refresh_token = config.refresh_token
+    case refresh_token  do
+      :nil -> # RAISE AN EXCEPTION DUE TO UNAVAILABILITY OF THE REFRESH TOKEN
+        error = "Valid refresh token not available"
+        LoggingUtils.log_return(error, :error)
+        raise error
+      refresh_token -> # TRY TO GET REFRESH TOKEN FROM THE CONFIG
+        tokens = get_latest_tokens(%{"refresh_token" => refresh_token}, config) |> Map.put(:lock, :false)
+        :ets.insert(ets_tablename(client), {:tokens, tokens})
+        Task.start_link(fn -> monitor_expiry(client, tokens["expires_in"]) end)
+        {:ok, {client, config, tokens}}
+    end
+  end
+
+  def handle_call(:add_lock, _from, {client, config, tokens}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    new_tokens = Map.put(tokens, :lock, :true)
+    :ets.insert(ets_tablename(client), {:tokens, new_tokens})
+    {:reply, :ok, new_tokens}
+  end
+
+  def handle_call(:remove_lock, _from, {client, config, tokens}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    new_tokens = Map.put(tokens, :lock, :false)
+    :ets.insert(ets_tablename(client), {:tokens, new_tokens})
+    {:reply, :ok, new_tokens}
+  end
+
+  def handle_call(:update_tokens, _from, {client, config, tokens}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    new_tokens = get_latest_tokens(tokens, config)
+    |> Map.put(tokens, :lock, :false)
+    :ets.insert(ets_tablename(client), {:tokens, new_tokens})
+    {:reply, :ok, {client, new_tokens}}
+  end
+
+  def handle_call(:get_config, _from, {client, config, tokens}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    {:reply, config, {client, config, tokens}}
+  end
+
+  def handle_call(:stop, _from, {client, config, tokens}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    {:stop, :shutdown, :ok, {client, config, tokens}}
+  end
+
+  def terminate(:shutdown, {client, config, tokens}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    :ets.delete(ets_tablename(client))
+    :ok
+  end
+
+
+  #####################
+  # Private
+  #####################
+
+  defp gen_server_name(client), do: String.to_atom(Atom.to_string(client) <> Atom.to_string(__MODULE__))
+  defp ets_tablename(client), do: String.to_atom("Ets" <> Atom.to_string(gen_server_name(client)))
+
+  # get the token from the :ets table
+  defp get_token(client, index) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    if ets_tablename(client) in :ets.all() do
+      [tokens: tokens] = :ets.lookup(ets_tablename(client), :tokens)
+      if tokens.lock === :true do
+        if index > @get_token_retries do
+          raise "Problem retrieving the access token from ets table"
+        else
+          :timer.sleep(@get_token_sleep_interval)
+          get_token(index + 1)
+        end
+      else
+        tokens["access_token"]
+      end
+    else
+      if index > @get_token_retries do
+        raise "Problem retrieving the access token from ets table"
+      else
+        :timer.sleep(@get_token_sleep_interval)
+        get_token(index + 1)
+      end
+    end
+  end
+
+
+  # Returns a map in following format with the latest tokens:
+  # %{"access_token" => "access_token", "expires_in" => 21600, "refresh_token" => "refresh_token", "token_type" => "Bearer"}
+  defp get_latest_tokens(tokens, config) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    Auth.get_latest_access_token(tokens["refresh_token"], config)
+    |> Map.put("refresh_token", tokens["refresh_token"])
+  end
+
+  # Recursive function
+  # Modifies the gen_server state every time the access_token expiry is within 30 seconds of expiry.
+  # expires_in parameter is in seconds
+  # This function is used as a worker `Task` everytime the genserver is initialised.
+  defp monitor_expiry(client, expires_in) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    interval = (expires_in - 30) * 1000
+    :timer.sleep(interval)
+    {:reply, :ok, _state} = GenServer.call(gen_server_name(client), :add_lock)
+    {:reply, :ok, _state} = GenServer.call(gen_server_name(client), :update_tokens)
+    {:reply, :ok, state} = GenServer.call(gen_server_name(client), :remove_lock)
+    monitor_expiry(client, state["expires_in"])
+  end
+
+  # creates the ets table
+  defp create_ets_table(client) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    ets_options = [
+                   :set, # type
+                   :protected, # read - all, write this process only.
+                   :named_table,
+                   {:heir, :none}, # don't let any process inherit the table. when the ets table dies, it dies.
+                   {:write_concurrency, :false},
+                   {:read_concurrency, :true}
+                  ]
+    unless ets_tablename(client) in :ets.all() do
+      :ets.new(ets_tablename(client), ets_options)
+    end
+  end
+
+
+end
\ No newline at end of file
diff --git a/lib/hubic/openstack/cache.ex b/lib/hubic/openstack/cache.ex
new file mode 100644
index 0000000..d442379
--- /dev/null
+++ b/lib/hubic/openstack/cache.ex
@@ -0,0 +1,182 @@
+defmodule ExOvh.Hubic.Openstack.Cache do
+  @moduledoc """
+  Caches the openstack credentials for access to the openstack api
+  Hubic does not use the standard Openstack Identity (Keystone) api for auth.
+  """
+  use GenServer
+  alias ExOvh.Hubic.Cache
+  alias ExOvh.Hubic.Request
+  @get_credentials_retries 10
+  @get_credentials_sleep_interval 150
+
+
+  #####################
+  # Public
+  #####################
+
+
+  @doc "Starts the genserver"
+  def start_link({client, config, opts}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    GenServer.start_link(__MODULE__, {client, config, opts}, [name: gen_server_name(client)])
+  end
+
+
+  def get_credentials(), do: get_credentials(ExOvh)
+  def get_credentials(client), do: get_credentials(client, 0)
+
+
+  def get_credentials_token(), do: get_credentials_token(ExOvh)
+  def get_credentials_token(client), do: get_credentials(client)["token"]
+
+
+  def get_endpoint(), do: get_endpoint(ExOvh)
+  def get_endpoint(client) do
+    credentials = get_credentials(client)
+    path = URI.parse(credentials["endpoint"])
+    |> Map.get(:path)
+    {version, account} = String.split_at(path, 4)
+    endpoint = List.first(String.split(credentials["endpoint"], account))
+    endpoint
+  end
+
+
+  def get_account(), do: get_account(ExOvh)
+  def get_account(client) do
+    credentials = get_credentials(client)
+    path = URI.parse(credentials["endpoint"])
+    |> Map.get(:path)
+    {version, account} = String.split_at(path, 4)
+    account
+  end
+
+
+  #####################
+  # Genserver Callbacks
+  #####################
+
+
+  # trap exits so that terminate callback is invoked
+  # the :lock key is to allow for locking during the brief moment that the access token is being refreshed
+  def init({client, config, opts}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    :erlang.process_flag(:trap_exit, :true)
+    token = Cache.get_token(client)
+    :timer.sleep(10_000) # give some time for TokenCache Genserver to initialize
+    create_ets_table(client)
+    {:ok, resp} = Request.request(client, {:get, "/account/credentials", ""})
+    credentials = Map.put(resp.body, :lock, :false)
+    :ets.insert(ets_tablename(client), {:credentials, credentials})
+    expires = to_seconds(credentials["expires"])
+    Task.start_link(fn -> monitor_expiry(client, expires) end)
+    {:ok, {client, config, credentials}}
+  end
+
+
+  def handle_call(:add_lock, _from, {client, config, credentials}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    new_credentials = Map.put(credentials, :lock, :true)
+    :ets.insert(ets_tablename(client), {:credentials, new_credentials})
+    {:reply, :ok, {client, config, new_credentials}}
+  end
+  def handle_call(:remove_lock, _from, {client, config, credentials}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    new_credentials = Map.put(credentials, :lock, :false)
+    :ets.insert(ets_tablename(client), {:credentials, new_credentials})
+    {:reply, :ok, {client, config, new_credentials}}
+  end
+  def handle_call(:update_credentials, _from, {client, config, credentials}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    {:ok, resp} = Request.request(client, {:get, "/account/credentials", ""})
+    new_credentials = resp.body
+    |> Map.put(credentials, :lock, :false)
+    :ets.insert(ets_tablename(client), {:credentials, new_credentials})
+    {:reply, :ok, {client, config, new_credentials}}
+  end
+  def handle_call(:stop, _from, state) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    {:stop, :shutdown, :ok, state}
+  end
+  def terminate(:shutdown, {client, config, credentials}) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    :ets.delete(ets_tablename(client)) # explicilty remove
+    :ok
+  end
+
+
+
+  #####################
+  # Private
+  #####################
+
+  defp gen_server_name(client), do: String.to_atom(Atom.to_string(client) <> Atom.to_string(__MODULE__))
+  defp ets_tablename(client), do: String.to_atom("Ets" <> Atom.to_string(gen_server_name(client)))
+
+
+  defp get_credentials(client, index) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    if ets_tablename(client) in :ets.all() do
+      [credentials: credentials] = :ets.lookup(ets_tablename(client), :credentials)
+      if credentials.lock === :true do
+        if index > @get_credentials_retries do
+          raise "Problem retrieving the openstack credentials from ets table"
+        else
+          :timer.sleep(@get_credentials_sleep_interval)
+          get_credentials(index + 1)
+        end
+      else
+        credentials
+      end
+    else
+      if index > @get_credentials_retries do
+        raise "Problem retrieving the openstack credentials from ets table"
+      else
+        :timer.sleep(@get_credentials_sleep_interval)
+        get_credentials(index + 1)
+      end
+    end
+  end
+
+
+  defp monitor_expiry(client, expires) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    interval = (expires - 30) * 1000
+    :timer.sleep(interval)
+    {:reply, :ok, _credentials} = GenServer.call(gen_server_name(client), :add_lock)
+    {:reply, :ok, _credentials} = GenServer.call(gen_server_name(client), :update_credentials)
+    {:reply, :ok, credentials} = GenServer.call(gen_server_name(client), :remove_lock)
+    expires = to_seconds(credentials["expires"])
+    monitor_expiry(client, expires)
+  end
+
+
+  defp create_ets_table(client) do
+    LoggingUtils.log_mod_func_line(__ENV__, :debug)
+    ets_options = [
+                   :set, # type
+                   :protected, # read - all, write this process only.
+                   :named_table,
+                   {:heir, :none}, # don't let any process inherit the table. when the ets table dies, it dies.
+                   {:write_concurrency, :false},
+                   {:read_concurrency, :true}
+                  ]
+    unless ets_tablename(client) in :ets.all() do
+      :ets.new(ets_tablename(client), ets_options)
+    end
+  end
+
+
+  defp to_seconds(iso_time) do
+    {:ok, expiry_ndt, offset} = Calendar.NaiveDateTime.Parse.iso8601(iso_time)
+    {:ok, expiry_dt_utc} = Calendar.NaiveDateTime.with_offset_to_datetime_utc(expiry_ndt, offset)
+    {:ok, now} = Calendar.DateTime.from_erl(:calendar.universal_time(), "UTC")
+    {:ok, seconds, _microseconds, _when} = Calendar.DateTime.diff(expiry_dt_utc, now)
+    if seconds > 0 do
+      seconds
+    else
+      0
+    end
+  end
+
+
+end
\ No newline at end of file
diff --git a/lib/hubic/openstack/request.ex b/lib/hubic/openstack/request.ex
new file mode 100644
index 0000000..fa0b629
--- /dev/null
+++ b/lib/hubic/openstack/request.ex
@@ -0,0 +1,44 @@
+defmodule ExOvh.Hubic.Openstack.Request do
+  alias ExOvh.Hubic.Openstack.Cache
+
+  ###################
+  # Public
+  ###################
+
+
+  @doc "For requests to the hubic openstack compliant api"
+  @spec request(method :: atom, path :: String.t, body :: String.t) :: map
+  def request(method, path, body \\ :nil) do
+    headers = ["X-Auth-Token": Cache.get_credentials_token()]
+    if method === :get do
+      headers = :lists.append(headers, ["Content-Type": "application/json"])
+    end
+    req_options = [ headers: headers, timeout: 10000 ]
+    fullpath =  Cache.get_endpoint() <> path
+    if body !== :nil do
+      resp = HTTPotion.request(method, fullpath, :lists.append(req_options, [body: body]))
+    else
+      resp = HTTPotion.request(method, fullpath, req_options)
+    end
+    if Map.has_key?(resp, :body) and not resp.body in [:nil, ""]  do
+      Poison.decode!(resp.body)
+    else
+      if resp.body in [:nil, ""] do
+        body
+      else
+        resp
+      end
+    end
+  end
+
+
+
+  ###################
+  # Private
+  ###################
+
+  #defp region(), do: "hubic"
+  #defp access(), do: "public"
+
+
+end
\ No newline at end of file
diff --git a/lib/hubic/openstack_cache.ex b/lib/hubic/openstack_cache.ex
deleted file mode 100644
index 5f97938..0000000
--- a/lib/hubic/openstack_cache.ex
+++ /dev/null
@@ -1,185 +0,0 @@
-defmodule ExOvh.Hubic.OpenstackCache do
-  @moduledoc """
-  Caches the openstack credentials for access to the openstack api
-  Hubic does not use the standard Openstack Identity (Keystone) api for auth.
-  """
-  use GenServer
-  alias ExOvh.Hubic.TokenCache
-  alias ExOvh.Hubic.Request
-  @get_credentials_retries 10
-  @get_credentials_sleep_interval 150
-
-
-  #####################
-  # Public
-  #####################
-
-
-  @doc "Starts the genserver"
-  def start_link({client, config, opts}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    GenServer.start_link(__MODULE__, {client, config, opts}, [name: gen_server_name(client)])
-  end
-
-
-  def get_credentials(), do: get_credentials(ExOvh)
-  def get_credentials(client), do: get_credentials(client, 0)
-
-
-  def get_credentials_token(), do: get_credentials_token(ExOvh)
-  def get_credentials_token(client), do: get_credentials(client)["token"]
-
-
-  def get_endpoint(), do: get_endpoint(ExOvh)
-  def get_endpoint(client) do
-    credentials = get_credentials(client)
-    path = URI.parse(credentials["endpoint"])
-    |> Map.get(:path)
-    {version, account} = String.split_at(path, 4)
-    endpoint = List.first(String.split(credentials["endpoint"], account))
-    endpoint
-  end
-
-
-  def get_account(), do: get_account(ExOvh)
-  def get_account(client) do
-    credentials = get_credentials(client)
-    path = URI.parse(credentials["endpoint"])
-    |> Map.get(:path)
-    {version, account} = String.split_at(path, 4)
-    account
-  end
-
-
-  #####################
-  # Genserver Callbacks
-  #####################
-
-
-  # trap exits so that terminate callback is invoked
-  # the :lock key is to allow for locking during the brief moment that the access token is being refreshed
-  def init({client, config, opts}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    :erlang.process_flag(:trap_exit, :true)
-    token = TokenCache.get_token(client)
-    |> LoggingUtils.log_return(:debug)
-    :timer.sleep(10_000) # give some time for TokenCache Genserver to initialize
-    create_ets_table(client)
-    credentials = Request.request(client, :get, "/account/credentials", "")
-    |> LoggingUtils.log_return
-    |> Map.put(:lock, :false)
-    |> LoggingUtils.log_return
-    :ets.insert(ets_tablename(client), {:credentials, credentials})
-    expires = to_seconds(credentials["expires"])
-    Task.start_link(fn -> monitor_expiry(client, expires) end)
-    {:ok, {client, config, credentials}}
-  end
-
-
-  def handle_call(:add_lock, _from, {client, config, credentials}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    new_credentials = Map.put(credentials, :lock, :true)
-    :ets.insert(ets_tablename(client), {:credentials, new_credentials})
-    {:reply, :ok, {client, config, new_credentials}}
-  end
-  def handle_call(:remove_lock, _from, {client, config, credentials}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    new_credentials = Map.put(credentials, :lock, :false)
-    :ets.insert(ets_tablename(client), {:credentials, new_credentials})
-    {:reply, :ok, {client, config, new_credentials}}
-  end
-  def handle_call(:update_credentials, _from, {client, config, credentials}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    new_credentials = Request.request(client, :get, "/account/credentials", "")
-    |> Map.put(credentials, :lock, :false)
-    :ets.insert(ets_tablename(client), {:credentials, new_credentials})
-    {:reply, :ok, {client, config, new_credentials}}
-  end
-  def handle_call(:stop, _from, state) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    {:stop, :shutdown, :ok, state}
-  end
-  def terminate(:shutdown, {client, config, credentials}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    :ets.delete(ets_tablename(client)) # explicilty remove
-    :ok
-  end
-
-
-
-  #####################
-  # Private
-  #####################
-
-  defp gen_server_name(client), do: String.to_atom(Atom.to_string(client) <> Atom.to_string(__MODULE__))
-  defp ets_tablename(client), do: String.to_atom("Ets" <> Atom.to_string(gen_server_name(client)))
-
-
-  defp get_credentials(client, index) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    if ets_tablename(client) in :ets.all() do
-      [credentials: credentials] = :ets.lookup(ets_tablename(client), :credentials)
-      if credentials.lock === :true do
-        if index > @get_credentials_retries do
-          raise "Problem retrieving the openstack credentials from ets table"
-        else
-          :timer.sleep(@get_credentials_sleep_interval)
-          get_credentials(index + 1)
-        end
-      else
-        credentials
-      end
-    else
-      if index > @get_credentials_retries do
-        raise "Problem retrieving the openstack credentials from ets table"
-      else
-        :timer.sleep(@get_credentials_sleep_interval)
-        get_credentials(index + 1)
-      end
-    end
-  end
-
-
-  defp monitor_expiry(client, expires) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    interval = (expires - 30) * 1000
-    :timer.sleep(interval)
-    LoggingUtils.log_return("monitor_expiry_openstack_credentials task is fetching new openstack credentials #{ets_tablename(client)}")
-    {:reply, :ok, _credentials} = GenServer.call(gen_server_name(client), :add_lock)
-    {:reply, :ok, _credentials} = GenServer.call(gen_server_name(client), :update_credentials)
-    {:reply, :ok, credentials} = GenServer.call(gen_server_name(client), :remove_lock)
-    expires = to_seconds(credentials["expires"])
-    monitor_expiry(client, expires)
-  end
-
-
-  defp create_ets_table(client) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    ets_options = [
-                   :set, # type
-                   :protected, # read - all, write this process only.
-                   :named_table,
-                   {:heir, :none}, # don't let any process inherit the table. when the ets table dies, it dies.
-                   {:write_concurrency, :false},
-                   {:read_concurrency, :true}
-                  ]
-    unless ets_tablename(client) in :ets.all() do
-      :ets.new(ets_tablename(client), ets_options)
-    end
-  end
-
-
-  defp to_seconds(iso_time) do
-    {:ok, expiry_ndt, offset} = Calendar.NaiveDateTime.Parse.iso8601(iso_time)
-    {:ok, expiry_dt_utc} = Calendar.NaiveDateTime.with_offset_to_datetime_utc(expiry_ndt, offset)
-    {:ok, now} = Calendar.DateTime.from_erl(:calendar.universal_time(), "UTC")
-    {:ok, seconds, _microseconds, _when} = Calendar.DateTime.diff(expiry_dt_utc, now)
-    if seconds > 0 do
-      seconds
-    else
-      0
-    end
-  end
-
-
-end
\ No newline at end of file
diff --git a/lib/hubic/request.ex b/lib/hubic/request.ex
index 52d8bd8..716b818 100644
--- a/lib/hubic/request.ex
+++ b/lib/hubic/request.ex
@@ -2,7 +2,8 @@ defmodule ExOvh.Hubic.Request do
   alias Poison
   alias HTTPotion
   alias ExOvh.Hubic.Auth
-  alias ExOvh.Hubic.TokenCache
+  alias ExOvh.Hubic.Cache, as: TokenCache
+  alias ExOvh.Hubic.Openstack.Cache
   alias ExOvh.Hubic.Defaults
 
 
@@ -12,44 +13,43 @@ defmodule ExOvh.Hubic.Request do
 
 
   @doc "Api for requests to the hubic custom api"
-  @spec request(method :: atom, uri :: String.t, params :: map, retries :: integer) :: map
-  def request(method, uri, params \\ :nil), do: request(ExOvh, method, uri, params, 0)
-
-
-  def request(client, method, uri, params, retries \\ 0) do
-    {method, uri, options} = Auth.prep_request(client, method, uri, params)
+  @spec request(query :: ExOvh.Client.raw_query_t)
+                :: {:ok, ExOvh.Client.response_t} | {:error, ExOvh.Client.response_t}
+  def request({method, uri, params} = query), do: request(ExOvh, query, 0)
+
+  @spec request(client :: atom, query :: ExOvh.Client.raw_query_t, retries :: integer)
+                :: {:ok, ExOvh.Client.response_t} | {:error, ExOvh.Client.response_t}
+  def request(client, {method, uri, params} = query, retries \\ 0) do
+    {method, uri, options} = Auth.prep_request(client, query)
     resp = HTTPotion.request(method, uri, options)
     resp =
     %{
       body: resp.body |> Poison.decode!(),
-      headers: resp.headers |> Enum.into(%{}),
+      headers: resp.headers,
       status_code: resp.status_code
     }
-    |> LoggingUtils.log_return(:debug)
-    body = resp |> Map.get(:body)
-    if Map.has_key?(body, "error") do
-      error = Map.get(body, "error") <> " :: " <> Map.get(body, "error_description")
-      if body["error"] === "invalid_token" do
-        # Restart the gen_server to recuperate state
-        GenServer.call(TokenCache, :stop)
-        # Try request one more time
-        unless retries >= 1 do
-          request(method, uri, body, 1)
+
+    if resp.status_code >= 100 and resp.status_code < 300 do
+     {:ok, resp}
+    else
+      if Map.has_key?(resp.body, "error") do
+        #error = Map.get(body, "error") <> " :: " <> Map.get(body, "error_description")
+        if resp.body["error"] === "invalid_token" do
+          GenServer.call(TokenCache, :stop) # Restart the gen_server to recuperate state
+          unless retries >= 1, do: request(query, 1) # Try request one more time
+        else
+          {:error, resp}
         end
       else
-        error
+        {:error, resp}
       end
-    else
-      body
     end
-  end
-
 
+  end
 
   ###################
   # Private
   ###################
 
 
-
 end
\ No newline at end of file
diff --git a/lib/hubic/supervisor.ex b/lib/hubic/supervisor.ex
index 44d6194..db286a3 100644
--- a/lib/hubic/supervisor.ex
+++ b/lib/hubic/supervisor.ex
@@ -4,8 +4,8 @@ defmodule ExOvh.Hubic.Supervisor do
   """
   use Supervisor
   alias LoggingUtils
-  alias ExOvh.Hubic.TokenCache
-  alias ExOvh.Hubic.OpenstackCache
+  alias ExOvh.Hubic.Cache, as: TokenCache
+  alias ExOvh.Hubic.Openstack.Cache, as: OpenstackCache
 
   #####################
   # Public
diff --git a/lib/hubic/token_cache.ex b/lib/hubic/token_cache.ex
deleted file mode 100644
index 83f6fd3..0000000
--- a/lib/hubic/token_cache.ex
+++ /dev/null
@@ -1,197 +0,0 @@
-defmodule ExOvh.Hubic.TokenCache do
-  @moduledoc ~s"""
-  Caches the access_token and provides a simple get_token() api to other modules through one function get_token()
-  Caches the hubic config map.
-
-  Maintains the access token so that:
-  - State is maintained in gen_server state but gen_server could be a bottleneck so it is also copied to a public ets table.
-  - So state is also stored in an ets table and is quickly and globally retrievable.
-  - State in :ets and :gen_server should be synchronised.
-  - It is automatically refreshed in the background when it expires
-  - If the gen_server crashes, it will attempt to re-establish the access token
-  - The refresh token by attempting the following:
-    - 1. Firstly, try to recuperate the refresh_token from a dets entry.
-    - 2. Secondly, by checking for the refresh_token in the config secret file.
-  - If both of the above methods fail, then ultimately the gen_server will crash and the user
-    will have to retrieve another refresh_token using the `mix hubic` task
-
-  tokens is a map with the following structure:
-  - `%{
-       :lock => :true,
-       "access_token" => "access_token",
-       "expires_in" => 21600,
-       "refresh_token" => "refresh_token",
-       "token_type" => "Bearer"
-    }`
-  """
-  use GenServer
-  alias ExOvh.Hubic.Auth
-  @get_token_retries 20
-  @get_token_sleep_interval 300
-
-
-  #####################
-  # Public
-  #####################
-
-
-  @doc "Starts the genserver"
-  def start_link({client, config, opts}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    GenServer.start_link(__MODULE__, {client, config, opts}, [name: gen_server_name(client)])
-  end
-
-
-  @doc "Gets the access_token from the :ets table"
-  @spec get_token() :: String.t
-  def get_token(), do: get_token(ExOvh, 0)
-
-  @doc "Gets the access_token from the :ets table"
-  @spec get_token(client :: atom) :: String.t
-  def get_token(client), do: get_token(client, 0)
-
-  @doc "Retrieves the hubic config map"
-  def get_config(client) do
-    GenServer.call(gen_server_name(client), :get_config)
-  end
-
-
-  #####################
-  # Genserver Callbacks
-  #####################
-
-  # trap exits so that terminate callback is invoked
-  # the :lock key is to allow for locking during the brief moment that the access token is being refreshed
-  def init({client, config, _opts}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    :erlang.process_flag(:trap_exit, :true)
-    create_ets_table(client)
-    refresh_token = config.refresh_token
-    case refresh_token  do
-      :nil -> # RAISE AN EXCEPTION DUE TO UNAVAILABILITY OF THE REFRESH TOKEN
-        error = "Valid refresh token not available"
-        LoggingUtils.log_return(error, :error)
-        raise error
-      refresh_token -> # TRY TO GET REFRESH TOKEN FROM THE CONFIG
-        LoggingUtils.log_return("init with refresh_token from config", :debug)
-        tokens = get_latest_tokens(%{"refresh_token" => refresh_token}, config) |> Map.put(:lock, :false)
-        |> LoggingUtils.log_return(:debug)
-        :ets.insert(ets_tablename(client), {:tokens, tokens})
-        Task.start_link(fn -> monitor_expiry(client, tokens["expires_in"]) end)
-        {:ok, {client, config, tokens}}
-    end
-  end
-
-  def handle_call(:add_lock, _from, {client, config, tokens}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    new_tokens = Map.put(tokens, :lock, :true)
-    :ets.insert(ets_tablename(client), {:tokens, new_tokens})
-    {:reply, :ok, new_tokens}
-  end
-
-  def handle_call(:remove_lock, _from, {client, config, tokens}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    new_tokens = Map.put(tokens, :lock, :false)
-    :ets.insert(ets_tablename(client), {:tokens, new_tokens})
-    {:reply, :ok, new_tokens}
-  end
-
-  def handle_call(:update_tokens, _from, {client, config, tokens}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    new_tokens = get_latest_tokens(tokens, config)
-    |> Map.put(tokens, :lock, :false)
-    :ets.insert(ets_tablename(client), {:tokens, new_tokens})
-    {:reply, :ok, {client, new_tokens}}
-  end
-
-  def handle_call(:get_config, _from, {client, config, tokens}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    {:reply, config, {client, config, tokens}}
-  end
-
-  def handle_call(:stop, _from, {client, config, tokens}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    {:stop, :shutdown, :ok, {client, config, tokens}}
-  end
-
-  def terminate(:shutdown, {client, config, tokens}) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    :ets.delete(ets_tablename(client))
-    :ok
-  end
-
-
-  #####################
-  # Private
-  #####################
-
-  defp gen_server_name(client), do: String.to_atom(Atom.to_string(client) <> Atom.to_string(__MODULE__))
-  defp ets_tablename(client), do: String.to_atom("Ets" <> Atom.to_string(gen_server_name(client)))
-
-  # get the token from the :ets table
-  defp get_token(client, index) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    if ets_tablename(client) in :ets.all() do
-      [tokens: tokens] = :ets.lookup(ets_tablename(client), :tokens)
-      if tokens.lock === :true do
-        if index > @get_token_retries do
-          raise "Problem retrieving the access token from ets table"
-        else
-          :timer.sleep(@get_token_sleep_interval)
-          get_token(index + 1)
-        end
-      else
-        tokens["access_token"]
-      end
-    else
-      if index > @get_token_retries do
-        raise "Problem retrieving the access token from ets table"
-      else
-        :timer.sleep(@get_token_sleep_interval)
-        get_token(index + 1)
-      end
-    end
-  end
-
-
-  # Returns a map in following format with the latest tokens:
-  # %{"access_token" => "access_token", "expires_in" => 21600, "refresh_token" => "refresh_token", "token_type" => "Bearer"}
-  defp get_latest_tokens(tokens, config) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    Auth.get_latest_access_token(tokens["refresh_token"], config)
-    |> Map.put("refresh_token", tokens["refresh_token"])
-  end
-
-  # Recursive function
-  # Modifies the gen_server state every time the access_token expiry is within 30 seconds of expiry.
-  # expires_in parameter is in seconds
-  # This function is used as a worker `Task` everytime the genserver is initialised.
-  defp monitor_expiry(client, expires_in) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    interval = (expires_in - 30) * 1000
-    :timer.sleep(interval)
-    LoggingUtils.log_return("monitor_expiry task is fetching a new access token #{ets_tablename(client)}")
-    {:reply, :ok, _state} = GenServer.call(gen_server_name(client), :add_lock)
-    {:reply, :ok, _state} = GenServer.call(gen_server_name(client), :update_tokens)
-    {:reply, :ok, state} = GenServer.call(gen_server_name(client), :remove_lock)
-    monitor_expiry(client, state["expires_in"])
-  end
-
-  # creates the ets table
-  defp create_ets_table(client) do
-    LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    ets_options = [
-                   :set, # type
-                   :protected, # read - all, write this process only.
-                   :named_table,
-                   {:heir, :none}, # don't let any process inherit the table. when the ets table dies, it dies.
-                   {:write_concurrency, :false},
-                   {:read_concurrency, :true}
-                  ]
-    unless ets_tablename(client) in :ets.all() do
-      :ets.new(ets_tablename(client), ets_options)
-    end
-  end
-
-
-end
\ No newline at end of file
diff --git a/lib/mix/tasks/hubic.ex b/lib/mix/tasks/hubic.ex
index a42610b..2a9878b 100644
--- a/lib/mix/tasks/hubic.ex
+++ b/lib/mix/tasks/hubic.ex
@@ -103,10 +103,16 @@ defmodule Mix.Tasks.Hubic do
                    "&scope=" <> "usage.r,account.r,getAllLinks.r,credentials.r,sponsorCode.r,activate.w,sponsored.r,links.drw" <>
                    "&response_type=" <> "code" <>
                    "&state=" <> SecureRandom.urlsafe_base64(10)
-    options = [ timeout: @timeout ]
+    options = %{ timeout: @timeout }
     uri = @hubic_auth_uri <> query_string
-    %HTTPotion.Response{body: resp_body, headers: headers, status_code: status} = HTTPotion.request(:get, uri, options)
-    inputs = get_validated_inputs(resp_body)
+    resp = HTTPotion.request(:get, uri, options)
+    resp =
+    %{
+      body: resp.body,
+      headers: resp.headers,
+      status_code: resp.status_code
+     }
+    inputs = get_validated_inputs(resp.body)
     {req_body, _, _} = Enum.reduce(inputs, {"", 1, Enum.count(inputs)}, fn({"input", input, _}, acc) ->
       name = :proplists.get_value("name", input)
       value = ""
@@ -131,12 +137,13 @@ defmodule Mix.Tasks.Hubic do
       end
       {acc, index + 1, max}
     end)
-    resp = HTTPotion.request(:post, @hubic_auth_uri, [body: req_body, headers: ["Content-Type": "application/x-www-form-urlencoded"]])
+    options = %{ body: req_body, headers: %{ "Content-Type": "application/x-www-form-urlencoded" } }
+    resp = HTTPotion.request(:post, @hubic_auth_uri, options)
     if resp.status_code !== 302, do: raise "Error getting hubic authorisation code with hubic config settings \n #{resp}"
     resp =
     %{
       body: resp.body,
-      headers: resp.headers |> Enum.into(%{}),
+      headers: resp.headers,
       status_code: resp.status_code
     }
     code = resp.headers
@@ -153,11 +160,8 @@ defmodule Mix.Tasks.Hubic do
     LoggingUtils.log_mod_func_line(__ENV__, :debug)
     inputs = Floki.find(resp_body, "form input[type=text], form input[type=password], form input[type=checkbox], form input[type=hidden]")
     |> List.flatten()
-    if Enum.any?(inputs, fn(input) -> input === [] end) do
-      raise "Inputs should not be empty"
-    else
-      inputs
-    end
+    if Enum.any?(inputs, fn(input) -> input === [] end), do: raise "Empty input found"
+    inputs
   end
 
   #- Adds the refresh_token to the opts_map
@@ -169,32 +173,25 @@ defmodule Mix.Tasks.Hubic do
     req_body = "code=" <> opts_map.auth_code <>
                "&redirect_uri=" <> URI.encode(opts_map.redirect_uri) <>
                "&grant_type=authorization_code"
-    headers = [
+    headers = %{
                "Content-Type": "application/x-www-form-urlencoded",
                "Authorization": "Basic " <> auth_credentials_base64
-              ]
-    req_options = [
-                  body: req_body,
-                  headers: headers,
-                  timeout: @timeout
-                  ]
-    resp = HTTPotion.request(:post, @hubic_token_uri, req_options)
+              }
+    options = %{ body: req_body, headers: headers, timeout: @timeout }
+    resp = HTTPotion.request(:post, @hubic_token_uri, options)
     now_milli_seconds = :os.system_time(:milli_seconds)
     body =
     %{
       body: resp.body |> Poison.decode!(),
-      headers: resp.headers |> Enum.into(%{}),
+      headers: resp.headers,
       status_code: resp.status_code
     }
-    |> LoggingUtils.log_return(:debug)
     |> Map.get(:body)
     if Map.has_key?(body, "error") do
       error = Map.get(resp, "error") <> " :: " <> Map.get(resp, "error_description")
       raise error
     end
     refresh_token = Map.get(body, "refresh_token")
-    refresh_token_expiry = now_milli_seconds + Map.get(body, "expires_in")
-    #Map.merge(opts_map, %{ refresh_token: refresh_token, refresh_token_expiry: refresh_token_expiry })
     Map.merge(opts_map, %{ refresh_token: refresh_token })
   end
 
diff --git a/lib/mix/tasks/ovh.ex b/lib/mix/tasks/ovh.ex
index c75c14a..ec2f57a 100644
--- a/lib/mix/tasks/ovh.ex
+++ b/lib/mix/tasks/ovh.ex
@@ -4,6 +4,7 @@ defmodule Mix.Tasks.Ovh do
   alias ExOvh.Ovh.Auth
 
   @shortdoc "Create a new app and new credentials for accessing ovh api"
+  @default_headers ["Content-Type": "application/json; charset=utf-8"]
   @timeout 10_000
 
   defp endpoint(config), do: Defaults.endpoints()[config[:endpoint]]
@@ -39,7 +40,7 @@ defmodule Mix.Tasks.Ovh do
         endpoint: \"#{options.endpoint}\",
         api_version: \"#{options.api_version}\"
        }
-        "
+       "
        Mix.Shell.IO.info(message)
     end
   end
@@ -153,7 +154,7 @@ defmodule Mix.Tasks.Ovh do
     LoggingUtils.log_mod_func_line(__ENV__, :debug)
     options = [ timeout: @timeout ]
     default_create_app_uri(opts_map)
-    %HTTPotion.Response{body: resp_body, headers: headers, status_code: status} =
+    %HTTPotion.Response{body: resp_body, headers: headers, status_code: status_code} =
       HTTPotion.request(:get, default_create_app_uri(opts_map), options)
     resp_body
   end
@@ -163,11 +164,8 @@ defmodule Mix.Tasks.Ovh do
     LoggingUtils.log_mod_func_line(__ENV__, :debug)
     inputs = Floki.find(resp_body, "form input")
     |> List.flatten()
-    if Enum.any?(inputs, fn(input) -> input === [] end) do
-      raise "Inputs should not be empty"
-    else
-      inputs
-    end
+    if Enum.any?(inputs, fn(input) -> input === [] end), do: raise "Empty input found"
+    inputs
   end
 
 
@@ -243,12 +241,10 @@ defmodule Mix.Tasks.Ovh do
 
   defp get_consumer_key(%{access_rules: access_rules, redirect_uri: redirect_uri} = opts_map) do
     LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    body = %{
-      accessRules: access_rules,
-      redirection: redirect_uri
-    }
-    {method, uri, options} = Auth.prep_request(opts_map, :post, consumer_key_uri(opts_map), body, :false)
-    options = Keyword.put(options, :headers, Keyword.get(options, :headers) ++ ["X-Ovh-Application": app_key(opts_map)])
+    body = %{ accessRules: access_rules, redirection: redirect_uri }
+    query = {:post, consumer_key_uri(opts_map), body}
+    {method, uri, options} = Auth.ovh_prep_request(opts_map, query)
+    options = Map.put(options, :headers, Map.merge(@default_headers, %{ "X-Ovh-Application": app_key(opts_map)}))
     body = HTTPotion.request(method, consumer_key_uri(opts_map), options) |> Map.get(:body) |> Poison.decode!()
     {Map.get(body, "consumerKey"), Map.get(body, "validationUrl")}
   end
@@ -269,11 +265,8 @@ defmodule Mix.Tasks.Ovh do
     |> Enum.filter(fn({type, input, options}) ->
       :proplists.get_value("name", input) !== "identifiant"
     end)
-    if Enum.any?(inputs, fn(input) -> input === [] end) do
-      raise "Inputs should not be empty"
-    else
-      inputs
-    end
+    if Enum.any?(inputs, fn(input) -> input === [] end), do: raise "Inputs should not be empty"
+    inputs
   end
 
 
@@ -345,24 +338,4 @@ defmodule Mix.Tasks.Ovh do
   end
 
 
-  defp shell_info_access_rules(access_rules) do
-    max = Enum.count(access_rules) - 1
-    Enum.with_index(access_rules)
-    |> Enum.map(fn({rule, int}) ->
-      if int < max do
-        "           %{
-                       method: \"#{rule.method}\",
-                       path: \"#{rule.path}\"
-                      },
-        "
-      else
-        "           %{
-                       method: \"#{rule.method}\",
-                       path: \"#{rule.path}\"
-                      }"
-      end
-    end)
-  end
-
-
 end
\ No newline at end of file
diff --git a/lib/ovh/auth.ex b/lib/ovh/auth.ex
index 1aecf34..1663b94 100644
--- a/lib/ovh/auth.ex
+++ b/lib/ovh/auth.ex
@@ -3,7 +3,7 @@ defmodule ExOvh.Ovh.Auth do
   alias ExOvh.Ovh.Defaults
   alias ExOvh.Ovh.Cache
 
-  @default_headers ["Content-Type": "application/json; charset=utf-8"]
+  @default_headers %{ "Content-Type": "application/json; charset=utf-8" }
   @methods [:get, :post, :put, :delete]
   @timeout 10_000
 
@@ -13,43 +13,31 @@ defmodule ExOvh.Ovh.Auth do
   ############################
 
 
-  @spec prep_request(method :: atom, uri :: String.t, params :: map, signed :: boolean) :: tuple
-  def prep_request(method, uri, params, signed \\ :true), do: prep_request(ExOvh, method, uri, params, signed)
+  @spec prep_request(query :: ExOvh.Client.raw_query_t)
+                     :: ExOvh.Client.query_t
+  def prep_request({method, uri, params} = query), do: prep_request(ExOvh, query)
 
-  @spec prep_request(client :: atom, method :: atom, uri :: String.t, params :: map, signed :: boolean) :: tuple
-  def prep_request(client, method, uri, params, signed)
+  @spec prep_request(client :: atom, query :: ExOvh.Client.raw_query_t)
+                     :: ExOvh.Client.query_t
+  def prep_request(client, query)
 
-  def prep_request(client, method, uri, params, :false) when method in [:get, :delete] do
-    uri = uri(config, uri)
-    if params !== :nil and params !== "", do: uri = uri <> URI.encode_query(params)
-    options = [ headers: headers([]), timeout: @timeout ]
-    {method, uri, options}
-  end
-
-  def prep_request(client, method, uri, params, :false) when method in [:post, :put] do
-    uri = uri(config, uri)
-    if params !== "" and params !== :nil, do: params = Poison.encode!(params)
-    options = [ body: params, headers: headers([]), timeout: @timeout ]
-    {method, uri, options}
-  end
-
-  def prep_request(client, method, uri, params, :true) when method in [:get, :delete] do
+  def prep_request(client, {method, uri, params} = query) when method in [:get, :delete] do
     uri = uri(config, uri)
     config = config(client)
     if params !== :nil and params !== "", do: uri = uri <> URI.encode_query(params)
     consumer_key = get_consumer_key(config)
     opts = [app_secret(config), app_key(config), consumer_key, Atom.to_string(method), uri, ""]
-    options = [ headers: headers(opts, client), timeout: @timeout ]
+    options = %{ headers: headers(opts, client), timeout: @timeout }
     {method, uri, options}
   end
 
-  def prep_request(client, method, uri, params, :true) when method in [:post, :put] do
+  def prep_request(client, {method, uri, params} = query) when method in [:post, :put] do
     uri = uri(config, uri)
     config = config(client)
     consumer_key = get_consumer_key(config)
     if params !== "" and params !== :nil and method in [:post, :put], do: params = Poison.encode!(params)
     opts = [app_secret(config), consumer_key, Atom.to_string(method), uri, params]
-    options = [ body: params, headers: headers(opts, client), timeout: @timeout ]
+    options = %{ body: params, headers: headers(opts, client), timeout: @timeout }
     {method, uri, options}
   end
 
@@ -60,16 +48,15 @@ defmodule ExOvh.Ovh.Auth do
   ############################
 
 
-  defp headers(opts) when opts === [], do: @default_headers
   defp headers([app_secret, app_key, consumer_key, method, uri, body] = opts, client) do
     time = :os.system_time(:seconds) + Cache.get_time_diff(client)
-    @default_headers ++
-    [
+    Map.merge(@default_headers,
+    %{
     "X-Ovh-Application": app_key,
     "X-Ovh-Consumer":    consumer_key,
     "X-Ovh-Timestamp":   time,
     "X-Ovh-Signature":   sign_request([app_secret, consumer_key, String.upcase(method), uri, body, time])
-    ]
+    })
   end
 
 
diff --git a/lib/ovh/cache.ex b/lib/ovh/cache.ex
index df5770f..b2fcd53 100644
--- a/lib/ovh/cache.ex
+++ b/lib/ovh/cache.ex
@@ -32,7 +32,6 @@ defmodule ExOvh.Ovh.Cache do
 
   def init({client, config, opts}) do
     LoggingUtils.log_mod_func_line(__ENV__, :debug)
-    LoggingUtils.log_return({client, config, opts}, :warn)
     diff = calculate_diff(config)
     {:ok, {config, diff}}
   end
@@ -71,7 +70,7 @@ defmodule ExOvh.Ovh.Cache do
 
   defp api_time_request(config) do
     time_uri = endpoint(config) <> api_version(config) <> "/auth/time"
-    options = [ headers: ["Content-Type": "application/json; charset=utf-8"], timeout: 10_000 ]
+    options = %{ headers: %{ "Content-Type": "application/json; charset=utf-8" }, timeout: 10_000 }
     api_time = HTTPotion.request(:get, time_uri, options) |> Map.get(:body) |> Poison.decode!()
   end
 
diff --git a/lib/ovh/request.ex b/lib/ovh/request.ex
index 450d12d..8599f46 100644
--- a/lib/ovh/request.ex
+++ b/lib/ovh/request.ex
@@ -9,21 +9,28 @@ defmodule ExOvh.Ovh.Request do
   ############################
 
 
-  @spec request(method :: atom, uri :: String.t, params :: map, signed :: boolean) :: map
-  def request(method, uri, params, signed) when signed === :true, do: request(ExOvh, method, uri, params, :true)
-  def request(method, uri, params, signed) when signed === :false, do: request(ExOvh, method, uri, params, :false)
+  @spec request(query :: ExOvh.Client.raw_query_t)
+               :: {:ok, map} | {:error, map}
+  def request({method, uri, params} = query), do: request(ExOvh, {method, uri, params} = query)
 
 
-  @spec request(client :: atom, method :: atom, uri :: String.t, params :: map, signed :: boolean) :: map
-  def request(client, method, uri, params, signed) do
+  @spec request(client :: atom, query :: ExOvh.Client.query_t)
+               :: {:ok, ExOvh.Client.response_t} | {:error, ExOvh.Client.response_t}
+  def request(client, {method, uri, params} = query) do
     config = config(client)
-    {method, uri, options} = Auth.prep_request(client, method, uri, params, signed)
+    {method, uri, options} = Auth.prep_request(client, query)
     resp = HTTPotion.request(method, uri, options)
+    resp =
     %{
       body: resp.body |> Poison.decode!(),
-      headers: resp.headers |> Enum.into(%{}),
+      headers: resp.headers,
       status_code: resp.status_code
     }
+    if resp.status_code >= 100 and resp.status_code < 300 do
+     {:ok, resp}
+    else
+     {:error, resp}
+    end
   end