dynamoxy 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/Cargo.lock +2 -17
  2. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/Cargo.toml +2 -4
  3. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/PKG-INFO +4 -2
  4. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/README.md +3 -1
  5. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/README.md +3 -1
  6. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/aws/convert.rs +2 -1
  7. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/batch.rs +22 -16
  8. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/items.rs +40 -29
  9. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/mod.rs +52 -4
  10. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/partiql.rs +2 -3
  11. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/query.rs +198 -69
  12. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/table.rs +50 -18
  13. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/tests.rs +216 -0
  14. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/transact.rs +61 -10
  15. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/client.rs +97 -64
  16. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/expr/mod.rs +1 -1
  17. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/expr/parser.rs +69 -67
  18. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/expr/projection.rs +28 -9
  19. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/expr/reserved.rs +15 -2
  20. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/value/number.rs +149 -2
  21. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-py/Cargo.toml +0 -1
  22. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-py/src/client.rs +118 -91
  23. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-py/src/convert.rs +188 -74
  24. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-py/src/errors.rs +13 -10
  25. dynamoxy-0.2.0/crates/dynamoxy-py/src/runtime.rs +566 -0
  26. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/AGENT_GUIDE.md +87 -12
  27. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/__init__.py +7 -1
  28. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/_pydantic.py +20 -4
  29. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/attributes.py +7 -2
  30. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/batch.py +28 -13
  31. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/client.py +164 -53
  32. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/codecs.py +36 -5
  33. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/collection.py +26 -4
  34. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/events.py +48 -13
  35. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/expressions.py +13 -7
  36. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/middleware.py +37 -15
  37. dynamoxy-0.2.0/python/dynamoxy/models.py +879 -0
  38. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/query.py +46 -12
  39. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/repository.py +177 -79
  40. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/schema.py +274 -65
  41. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/table.py +21 -5
  42. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/telemetry.py +55 -3
  43. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/transactions.py +20 -9
  44. dynamoxy-0.1.0/crates/dynamoxy-py/src/runtime.rs +0 -171
  45. dynamoxy-0.1.0/python/dynamoxy/models.py +0 -461
  46. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/LICENSE +0 -0
  47. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/Cargo.toml +0 -0
  48. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/aws/errors.rs +0 -0
  49. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/aws/mod.rs +0 -0
  50. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/memory/admin.rs +0 -0
  51. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/backend/mod.rs +0 -0
  52. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/client/tests.rs +0 -0
  53. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/config.rs +0 -0
  54. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/error.rs +0 -0
  55. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/events.rs +0 -0
  56. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/expr/ast.rs +0 -0
  57. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/expr/eval.rs +0 -0
  58. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/expr/tests.rs +0 -0
  59. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/expr/update.rs +0 -0
  60. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/lib.rs +0 -0
  61. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/metrics.rs +0 -0
  62. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/retry.rs +0 -0
  63. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/types/mod.rs +0 -0
  64. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/types/ops.rs +0 -0
  65. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/types/schema.rs +0 -0
  66. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/value/mod.rs +0 -0
  67. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/src/value/size.rs +0 -0
  68. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-core/tests/emulator.rs +0 -0
  69. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/crates/dynamoxy-py/src/lib.rs +0 -0
  70. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/pyproject.toml +0 -0
  71. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/__main__.py +0 -0
  72. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/_core.pyi +0 -0
  73. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/_utils.py +0 -0
  74. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/constraints.py +0 -0
  75. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/errors.py +0 -0
  76. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/py.typed +0 -0
  77. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/results.py +0 -0
  78. {dynamoxy-0.1.0 → dynamoxy-0.2.0}/python/dynamoxy/testing.py +0 -0
@@ -670,7 +670,7 @@ checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813"
670
670
 
671
671
  [[package]]
672
672
  name = "dynamoxy-core"
673
- version = "0.1.0"
673
+ version = "0.2.0"
674
674
  dependencies = [
675
675
  "async-trait",
676
676
  "aws-config",
@@ -686,12 +686,11 @@ dependencies = [
686
686
 
687
687
  [[package]]
688
688
  name = "dynamoxy-py"
689
- version = "0.1.0"
689
+ version = "0.2.0"
690
690
  dependencies = [
691
691
  "dynamoxy-core",
692
692
  "parking_lot",
693
693
  "pyo3",
694
- "pyo3-async-runtimes",
695
694
  "pythonize",
696
695
  "serde",
697
696
  "tokio",
@@ -1394,20 +1393,6 @@ dependencies = [
1394
1393
  "pyo3-macros",
1395
1394
  ]
1396
1395
 
1397
- [[package]]
1398
- name = "pyo3-async-runtimes"
1399
- version = "0.29.0"
1400
- source = "registry+https://github.com/rust-lang/crates.io-index"
1401
- checksum = "b3ef68daa7316a3fac65e5e18b2203f010346de1c1c53456811a2624673ab046"
1402
- dependencies = [
1403
- "futures-channel",
1404
- "futures-util",
1405
- "once_cell",
1406
- "pin-project-lite",
1407
- "pyo3",
1408
- "tokio",
1409
- ]
1410
-
1411
1396
  [[package]]
1412
1397
  name = "pyo3-build-config"
1413
1398
  version = "0.29.3"
@@ -4,7 +4,7 @@ members = ["crates/dynamoxy-core", "crates/dynamoxy-py"]
4
4
 
5
5
  # The single version of the project: the Python package takes it from the binding crate.
6
6
  [workspace.package]
7
- version = "0.1.0"
7
+ version = "0.2.0"
8
8
  edition = "2024"
9
9
  rust-version = "1.94"
10
10
  license = "MIT"
@@ -13,7 +13,7 @@ homepage = "https://github.com/kalaspuff/dynamoxy"
13
13
  authors = ["Carl Oscar Aaro <hello@carloscar.com>"]
14
14
 
15
15
  [workspace.dependencies]
16
- dynamoxy-core = { path = "crates/dynamoxy-core", version = "0.1.0" }
16
+ dynamoxy-core = { path = "crates/dynamoxy-core", version = "0.2.0" }
17
17
  async-trait = "0.1"
18
18
  aws-config = { version = "1.12", features = ["behavior-version-latest"] }
19
19
  aws-credential-types = { version = "1.3", features = ["hardcoded-credentials"] }
@@ -21,8 +21,6 @@ aws-sdk-dynamodb = { version = "1.130", features = ["behavior-version-latest"] }
21
21
  fastrand = "2"
22
22
  parking_lot = "0.12"
23
23
  pyo3 = { version = "0.29", features = ["abi3-py312"] }
24
- # tokio-runtime: implements the bridge's JoinError trait for Tokio (needed by runtime.rs).
25
- pyo3-async-runtimes = { version = "0.29", features = ["tokio-runtime"] }
26
24
  pythonize = "0.29"
27
25
  serde = { version = "1", features = ["derive"] }
28
26
  thiserror = "2"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: dynamoxy
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Classifier: Development Status :: 3 - Alpha
5
5
  Classifier: Framework :: AsyncIO
6
6
  Classifier: Framework :: Pydantic :: 2
@@ -71,7 +71,9 @@ async def main() -> None:
71
71
  users = client.repository(User)
72
72
 
73
73
  ada = await users.create(User(user_id="u1", email="ada@example.com", name="Ada"))
74
- await users.update(ada, User.visits.add(1)) # atomic; `ada` is refreshed in place
74
+ await ada.increment(User.visits) # atomic; `ada` is refreshed in place
75
+ ada.name = "Ada Lovelace"
76
+ await ada.save() # only if nobody changed it meanwhile (version)
75
77
 
76
78
  try:
77
79
  await users.create(User(user_id="u2", email="ada@example.com", name="Imposter"))
@@ -30,7 +30,9 @@ async def main() -> None:
30
30
  users = client.repository(User)
31
31
 
32
32
  ada = await users.create(User(user_id="u1", email="ada@example.com", name="Ada"))
33
- await users.update(ada, User.visits.add(1)) # atomic; `ada` is refreshed in place
33
+ await ada.increment(User.visits) # atomic; `ada` is refreshed in place
34
+ ada.name = "Ada Lovelace"
35
+ await ada.save() # only if nobody changed it meanwhile (version)
34
36
 
35
37
  try:
36
38
  await users.create(User(user_id="u2", email="ada@example.com", name="Imposter"))
@@ -30,7 +30,9 @@ async def main() -> None:
30
30
  users = client.repository(User)
31
31
 
32
32
  ada = await users.create(User(user_id="u1", email="ada@example.com", name="Ada"))
33
- await users.update(ada, User.visits.add(1)) # atomic; `ada` is refreshed in place
33
+ await ada.increment(User.visits) # atomic; `ada` is refreshed in place
34
+ ada.name = "Ada Lovelace"
35
+ await ada.save() # only if nobody changed it meanwhile (version)
34
36
 
35
37
  try:
36
38
  await users.create(User(user_id="u2", email="ada@example.com", name="Imposter"))
@@ -54,7 +54,8 @@ pub fn item_to_sdk(item: Item) -> HashMap<String, sdk::AttributeValue> {
54
54
  }
55
55
 
56
56
  fn number(text: String) -> Result<Number> {
57
- Number::parse(&text).map_err(|error| protocol_error(format!("invalid number {text:?}: {error}")))
57
+ // DynamoDB returns canonical numbers: they are kept as they are, without a copy.
58
+ Number::parse_owned(text).map_err(|error| protocol_error(format!("invalid number: {error}")))
58
59
  }
59
60
 
60
61
  /// Converts a value from the SDK's representation.
@@ -7,7 +7,7 @@ use super::State;
7
7
  use super::items::{Failure, apply, prepare_delete, prepare_put};
8
8
  use super::table::{CapacityMeter, StoredKey, read_units};
9
9
  use crate::error::{Error, Result};
10
- use crate::expr::{ExpressionInput, parse_request, project};
10
+ use crate::expr::{ExpressionInput, Projector, parse_request};
11
11
  use crate::types::{
12
12
  BatchGetItemInput, BatchGetItemOutput, BatchWriteItemInput, BatchWriteItemOutput, KeysAndAttributes,
13
13
  ReturnValuesOnConditionCheckFailure, WriteRequest,
@@ -32,7 +32,7 @@ pub fn batch_get_item(state: &State, input: &BatchGetItemInput, unprocessed: boo
32
32
  if total > 100 {
33
33
  return Err(invalid("Too many items requested for the BatchGetItem call"));
34
34
  }
35
- let mut parsed_projections = BTreeMap::new();
35
+ let mut parsed = Vec::with_capacity(input.request_items.len());
36
36
  for (table_name, request) in &input.request_items {
37
37
  if request.keys.is_empty() {
38
38
  return Err(invalid(format!(
@@ -40,18 +40,23 @@ pub fn batch_get_item(state: &State, input: &BatchGetItemInput, unprocessed: boo
40
40
  )));
41
41
  }
42
42
  let table = state.table(table_name)?;
43
- let mut seen = BTreeSet::new();
44
- for key in &request.keys {
45
- if !seen.insert(table.key.exact_key(key)?) {
43
+ let mut positions = BTreeMap::new();
44
+ for (position, key) in request.keys.iter().enumerate() {
45
+ if positions.insert(table.key.exact_key(key)?, position).is_some() {
46
46
  return Err(invalid("Provided list of item keys contains duplicates"));
47
47
  }
48
48
  }
49
- let parsed = parse_request(
49
+ let mut stored: Vec<Option<StoredKey>> = vec![None; request.keys.len()];
50
+ for (key, position) in positions {
51
+ stored[position] = Some(key);
52
+ }
53
+ let projection = parse_request(
50
54
  ExpressionInput { projection: request.projection_expression.as_deref(), ..Default::default() },
51
55
  &request.expression_attribute_names,
52
56
  &Default::default(),
53
- )?;
54
- parsed_projections.insert(table_name.clone(), parsed.projection);
57
+ )?
58
+ .projection;
59
+ parsed.push((stored, projection.as_deref().map(Projector::new)));
55
60
  }
56
61
  let mut output = BatchGetItemOutput::default();
57
62
  if unprocessed {
@@ -60,10 +65,9 @@ pub fn batch_get_item(state: &State, input: &BatchGetItemInput, unprocessed: boo
60
65
  }
61
66
  let mut meter = CapacityMeter::default();
62
67
  let mut returned = 0usize;
63
- for (table_name, request) in &input.request_items {
68
+ for ((table_name, request), (stored_keys, projection)) in input.request_items.iter().zip(&parsed) {
64
69
  let table = state.table(table_name)?;
65
- let projection = parsed_projections.get(table_name).and_then(Option::as_ref);
66
- for key in &request.keys {
70
+ for (key, stored) in request.keys.iter().zip(stored_keys) {
67
71
  if returned >= RESPONSE_SIZE_LIMIT {
68
72
  output
69
73
  .unprocessed_keys
@@ -73,12 +77,11 @@ pub fn batch_get_item(state: &State, input: &BatchGetItemInput, unprocessed: boo
73
77
  .push(key.clone());
74
78
  continue;
75
79
  }
76
- let stored: StoredKey = table.key.exact_key(key)?;
77
- let found = table.items.get(&stored);
80
+ let found = stored.as_ref().and_then(|stored| table.items.get(stored));
78
81
  meter.read(table_name, None, read_units(found.map_or(0, item_size), request.consistent_read));
79
82
  if let Some(item) = found {
80
83
  let item = match projection {
81
- Some(paths) => project(item, paths),
84
+ Some(projector) => projector.apply(item),
82
85
  None => item.clone(),
83
86
  };
84
87
  returned += item_size(&item);
@@ -142,8 +145,11 @@ pub fn batch_write_item(
142
145
  for write in prepared {
143
146
  if input.return_item_collection_metrics
144
147
  && let Some(table) = state.tables.get(&write.table)
145
- && let Some(metrics) =
146
- write.new.as_ref().or(write.old.as_ref()).and_then(|item| table.item_collection_metrics(item))
148
+ && let Some(metrics) = write
149
+ .new
150
+ .as_ref()
151
+ .or_else(|| table.items.get(&write.key))
152
+ .and_then(|item| table.item_collection_metrics(item))
147
153
  {
148
154
  output.item_collection_metrics.entry(write.table.clone()).or_default().push(metrics);
149
155
  }
@@ -39,23 +39,30 @@ impl Failure {
39
39
  }
40
40
  }
41
41
 
42
- /// A validated write, ready to apply.
42
+ /// A validated write, ready to apply. The item it replaces is still in the table until
43
+ /// [`apply`] returns it.
43
44
  #[derive(Debug)]
44
45
  pub struct Prepared {
45
46
  /// Table name.
46
47
  pub table: String,
47
48
  /// Key of the item.
48
49
  pub key: StoredKey,
49
- /// The item before the write.
50
- pub old: Option<Item>,
51
50
  /// The item after the write (`None`: deleted or does not exist).
52
51
  pub new: Option<Item>,
53
52
  /// Whether anything is written (`false` for condition checks).
54
53
  pub writes: bool,
54
+ /// Size of the item a condition check read (for its capacity).
55
+ pub read_size: usize,
55
56
  /// Paths written by an update (for `UPDATED_OLD` / `UPDATED_NEW`).
56
57
  pub updated_paths: Vec<crate::expr::Path>,
57
58
  }
58
59
 
60
+ impl Prepared {
61
+ fn write(table: &Table, key: StoredKey, new: Option<Item>, updated_paths: Vec<crate::expr::Path>) -> Self {
62
+ Self { table: table.name.clone(), key, new, writes: true, read_size: 0, updated_paths }
63
+ }
64
+ }
65
+
59
66
  fn check_condition(
60
67
  condition: Option<&Condition>,
61
68
  old: Option<&Item>,
@@ -81,9 +88,8 @@ pub fn prepare_put(
81
88
  return_on_failure: ReturnValuesOnConditionCheckFailure,
82
89
  ) -> Result<Prepared, Failure> {
83
90
  let key = table.validate_item(&item)?;
84
- let old = table.items.get(&key).cloned();
85
- check_condition(condition, old.as_ref(), return_on_failure)?;
86
- Ok(Prepared { table: table.name.clone(), key, old, new: Some(item), writes: true, updated_paths: Vec::new() })
91
+ check_condition(condition, table.items.get(&key), return_on_failure)?;
92
+ Ok(Prepared::write(table, key, Some(item), Vec::new()))
87
93
  }
88
94
 
89
95
  /// Prepares a `DeleteItem`.
@@ -94,9 +100,8 @@ pub fn prepare_delete(
94
100
  return_on_failure: ReturnValuesOnConditionCheckFailure,
95
101
  ) -> Result<Prepared, Failure> {
96
102
  let key = table.key.exact_key(key)?;
97
- let old = table.items.get(&key).cloned();
98
- check_condition(condition, old.as_ref(), return_on_failure)?;
99
- Ok(Prepared { table: table.name.clone(), key, old, new: None, writes: true, updated_paths: Vec::new() })
103
+ check_condition(condition, table.items.get(&key), return_on_failure)?;
104
+ Ok(Prepared::write(table, key, None, Vec::new()))
100
105
  }
101
106
 
102
107
  /// Prepares a condition check (transactions).
@@ -107,9 +112,10 @@ pub fn prepare_check(
107
112
  return_on_failure: ReturnValuesOnConditionCheckFailure,
108
113
  ) -> Result<Prepared, Failure> {
109
114
  let key = table.key.exact_key(key)?;
110
- let old = table.items.get(&key).cloned();
111
- check_condition(condition, old.as_ref(), return_on_failure)?;
112
- Ok(Prepared { table: table.name.clone(), key, new: old.clone(), old, writes: false, updated_paths: Vec::new() })
115
+ let old = table.items.get(&key);
116
+ check_condition(condition, old, return_on_failure)?;
117
+ let read_size = old.map_or(0, item_size);
118
+ Ok(Prepared { table: table.name.clone(), key, new: None, writes: false, read_size, updated_paths: Vec::new() })
113
119
  }
114
120
 
115
121
  /// Validates an update against the table's key (before any item is looked at).
@@ -127,25 +133,28 @@ pub fn prepare_update(
127
133
  return_on_failure: ReturnValuesOnConditionCheckFailure,
128
134
  ) -> Result<Prepared, Failure> {
129
135
  let stored = table.key.exact_key(key)?;
130
- let old = table.items.get(&stored).cloned();
131
- check_condition(condition, old.as_ref(), return_on_failure)?;
132
- let base = old.clone().unwrap_or_else(|| key.clone());
136
+ let old = table.items.get(&stored);
137
+ check_condition(condition, old, return_on_failure)?;
138
+ let base = old.unwrap_or(key);
133
139
  let (new, updated_paths) = match update {
134
- Some(update) => (apply_update(update, &base)?, update.paths().cloned().collect()),
135
- None => (base, Vec::new()),
140
+ Some(update) => (apply_update(update, base)?, update.paths().cloned().collect()),
141
+ None => (base.clone(), Vec::new()),
136
142
  };
137
143
  table.validate_item(&new)?;
138
- Ok(Prepared { table: table.name.clone(), key: stored, old, new: Some(new), writes: true, updated_paths })
144
+ Ok(Prepared::write(table, stored, Some(new), updated_paths))
139
145
  }
140
146
 
141
- /// Applies a prepared write and records its capacity. Returns the old item.
147
+ /// Applies a prepared write and records its capacity. Returns the item it replaced or deleted
148
+ /// (condition checks write nothing and return `None`).
142
149
  pub fn apply(state: &mut State, prepared: Prepared, meter: &mut CapacityMeter, multiplier: f64) -> Option<Item> {
143
- let Some(table) = state.tables.get_mut(&prepared.table) else { return prepared.old };
144
- meter.write(table, prepared.old.as_ref(), prepared.new.as_ref(), multiplier);
145
- if prepared.writes {
146
- table.write(prepared.key, prepared.new);
150
+ let table = state.tables.get_mut(&prepared.table)?;
151
+ if !prepared.writes {
152
+ return None;
147
153
  }
148
- prepared.old
154
+ let old = table.write(&prepared.key, prepared.new);
155
+ let table = &*table;
156
+ meter.write(table, old.as_ref(), table.items.get(&prepared.key), multiplier);
157
+ old
149
158
  }
150
159
 
151
160
  /// `PutItem` and `DeleteItem` only return the old item.
@@ -216,7 +225,7 @@ pub fn delete_item(state: &mut State, input: DeleteItemInput) -> Result<WriteIte
216
225
  prepare_delete(table, &input.key, parsed.condition.as_ref(), input.return_values_on_condition_check_failure)
217
226
  .map_err(Failure::into_error)?;
218
227
  let metrics = if input.return_item_collection_metrics {
219
- prepared.old.as_ref().and_then(|item| table.item_collection_metrics(item))
228
+ table.items.get(&prepared.key).and_then(|item| table.item_collection_metrics(item))
220
229
  } else {
221
230
  None
222
231
  };
@@ -258,17 +267,19 @@ pub fn update_item(state: &mut State, input: UpdateItemInput) -> Result<WriteIte
258
267
  } else {
259
268
  None
260
269
  };
261
- let new = prepared.new.clone();
262
- let paths = prepared.updated_paths.clone();
270
+ let mut prepared = prepared;
271
+ let paths = std::mem::take(&mut prepared.updated_paths);
263
272
  let table_name = prepared.table.clone();
273
+ let key = prepared.key.clone();
264
274
  let old = apply(state, prepared, &mut meter, 1.0);
275
+ let new = || state.tables.get(&table_name).and_then(|table| table.items.get(&key));
265
276
  let non_empty = |item: Item| (!item.is_empty()).then_some(item);
266
277
  let attributes = match input.return_values {
267
278
  ReturnValues::None => None,
268
279
  ReturnValues::AllOld => old,
269
- ReturnValues::AllNew => new,
280
+ ReturnValues::AllNew => new().cloned(),
270
281
  ReturnValues::UpdatedOld => old.and_then(|old| non_empty(project(&old, &paths))),
271
- ReturnValues::UpdatedNew => new.and_then(|new| non_empty(project(&new, &paths))),
282
+ ReturnValues::UpdatedNew => new().and_then(|new| non_empty(project(new, &paths))),
272
283
  };
273
284
  Ok(WriteItemOutput {
274
285
  attributes,
@@ -25,7 +25,7 @@ mod table;
25
25
  mod tests;
26
26
  mod transact;
27
27
 
28
- use std::collections::{BTreeMap, HashMap};
28
+ use std::collections::{BTreeMap, HashMap, VecDeque};
29
29
  use std::sync::Arc;
30
30
  use std::time::{Duration, SystemTime, UNIX_EPOCH};
31
31
 
@@ -71,6 +71,54 @@ pub(crate) struct TokenRecord {
71
71
  at: f64,
72
72
  }
73
73
 
74
+ /// How long a client request token is remembered (10 minutes).
75
+ pub(crate) const TOKEN_LIFETIME: f64 = 600.0;
76
+
77
+ /// Client request tokens of the last [`TOKEN_LIFETIME`] seconds. Expired tokens are forgotten in
78
+ /// arrival order, so each transaction does work proportional to what expired, not to every
79
+ /// token remembered.
80
+ #[derive(Debug, Default)]
81
+ pub(crate) struct Tokens {
82
+ records: HashMap<String, TokenRecord>,
83
+ arrivals: VecDeque<(f64, String)>,
84
+ }
85
+
86
+ impl Tokens {
87
+ /// Forgets the tokens that expired at `now`.
88
+ fn expire(&mut self, now: f64) {
89
+ while let Some((at, _)) = self.arrivals.front()
90
+ && now - *at >= TOKEN_LIFETIME
91
+ {
92
+ if let Some((at, token)) = self.arrivals.pop_front()
93
+ && self.records.get(&token).is_some_and(|record| record.at == at)
94
+ {
95
+ self.records.remove(&token);
96
+ }
97
+ }
98
+ }
99
+
100
+ /// The record of `token` if it has not expired at `now`.
101
+ fn get(&mut self, token: &str, now: f64) -> Option<&TokenRecord> {
102
+ self.expire(now);
103
+ // Arrivals are in clock order unless the clock went back: check the age too.
104
+ self.records.get(token).filter(|record| now - record.at < TOKEN_LIFETIME)
105
+ }
106
+
107
+ fn insert(&mut self, token: String, record: TokenRecord) {
108
+ self.arrivals.push_back((record.at, token.clone()));
109
+ self.records.insert(token, record);
110
+ }
111
+
112
+ fn remove(&mut self, token: &str) {
113
+ self.records.remove(token);
114
+ }
115
+
116
+ fn clear(&mut self) {
117
+ self.records.clear();
118
+ self.arrivals.clear();
119
+ }
120
+ }
121
+
74
122
  /// What an injected fault does.
75
123
  #[derive(Clone, Debug, PartialEq)]
76
124
  pub enum FaultKind {
@@ -105,7 +153,7 @@ pub struct Fault {
105
153
  pub(crate) struct State {
106
154
  tables: BTreeMap<String, Table>,
107
155
  backups: BTreeMap<String, Backup>,
108
- tokens: HashMap<String, TokenRecord>,
156
+ tokens: Tokens,
109
157
  faults: Vec<Fault>,
110
158
  region: String,
111
159
  account_id: String,
@@ -137,7 +185,7 @@ impl MemoryBackend {
137
185
  state: Arc::new(Mutex::new(State {
138
186
  tables: BTreeMap::new(),
139
187
  backups: BTreeMap::new(),
140
- tokens: HashMap::new(),
188
+ tokens: Tokens::default(),
141
189
  faults: Vec::new(),
142
190
  region: region.to_owned(),
143
191
  account_id: account_id.to_owned(),
@@ -176,7 +224,7 @@ impl MemoryBackend {
176
224
  .map(|(key, _)| key.clone())
177
225
  .collect();
178
226
  for key in expired {
179
- table.write(key, None);
227
+ table.write(&key, None);
180
228
  deleted += 1;
181
229
  }
182
230
  }
@@ -718,9 +718,9 @@ fn prepare_write(state: &State, statement: &Statement) -> Result<(Prepared, Retu
718
718
  let prepared = Prepared {
719
719
  table: table.name.clone(),
720
720
  key: stored,
721
- old: None,
722
721
  new: None,
723
722
  writes: false,
723
+ read_size: 0,
724
724
  updated_paths: Vec::new(),
725
725
  };
726
726
  return Ok((prepared, *returning));
@@ -979,8 +979,7 @@ pub fn execute_transaction(state: &mut State, input: &ExecuteTransactionInput) -
979
979
  hasher.finish()
980
980
  };
981
981
  let current = now();
982
- state.tokens.retain(|_, record| current - record.at < 600.0);
983
- if let Some(record) = state.tokens.get(token) {
982
+ if let Some(record) = state.tokens.get(token, current) {
984
983
  if record.fingerprint != fingerprint {
985
984
  return Err(ServiceError::new(
986
985
  "IdempotentParameterMismatchException",