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
//! Shapes of Cloudflare Durable Object stub calls.
//!
//! A Worker reads a Durable Object through a namespace binding, typed
//! `DurableObjectNamespace<C>`. A call of `get()` or `getByName()` on that
//! binding gives an RPC stub, and a method call on the stub runs the method of
//! the class `C`. The namespace type itself resolves to `C` (see
//! `MEMBER_PRESERVING_WRAPPERS`), so a stub local is an alias of the namespace
//! receiver.
//!
//! `get()` makes a stub only when its id argument comes from the same
//! namespace (`<ns>.idFromName(...)` inline, or a local that holds such a
//! call). A `get()` on a `Map` or on a repository therefore makes no alias.
//!
//! Because the namespace type resolves to `C`, a namespace method call such
//! as `env.NS.get(...)` reads like a call of `C.get`. Such a call gives no
//! credit when the same function proves that `env.NS` is a namespace: a
//! `get()` call on it takes an id of the same namespace. A call through a
//! stub local (`stub.get()`) always gives credit.
use oxc_ast::ast::*;
use rustc_hash::{FxHashMap, FxHashSet};
use super::{StructuralParamMemberCollector, unwrap_static_expr};
/// A local that reads a property path of a tracked parameter.
pub(super) struct ReceiverAlias {
/// The tracked parameter and the property path.
pub(super) target: (String, String),
/// The local holds a Durable Object stub of the namespace at `target`.
pub(super) stub: bool,
/// More parameter paths that the local can hold, for a conditional init
/// with branches on different paths. A read on the local reads each one.
pub(super) alternatives: Vec<(String, String)>,
}
impl ReceiverAlias {
pub(super) fn plain(target: (String, String)) -> Self {
Self {
target,
stub: false,
alternatives: Vec::new(),
}
}
}
/// A receiver that resolves to a property path of a tracked parameter.
pub(super) struct ResolvedReceiver {
pub(super) param: String,
pub(super) path: String,
/// The receiver reads the path through a Durable Object stub local.
pub(super) via_stub: bool,
}
/// The Durable Object calls of one function body.
#[derive(Default)]
pub(super) struct DurableObjectCalls {
/// Locals that hold a Durable Object id, mapped to the parameter and the
/// namespace path that made the id.
ids: FxHashMap<String, (String, String)>,
/// Parameter paths that a `get()` with an id of the same namespace
/// proves to be a Durable Object namespace.
namespaces: FxHashSet<(String, String)>,
/// Direct accesses of a namespace method name, as (parameter, path,
/// member). Each one becomes a member access at the end of the body,
/// unless its path is in `namespaces`.
method_accesses: Vec<(String, String, String)>,
}
impl DurableObjectCalls {
/// `local` holds a Durable Object id of a namespace receiver.
pub(super) fn holds_id(&self, local: &str) -> bool {
self.ids.contains_key(local)
}
}
/// Namespace methods that make a Durable Object id.
const ID_FACTORY_METHODS: &[&str] = &["idFromName", "idFromString", "newUniqueId"];
/// The methods of `DurableObjectNamespace`.
const NAMESPACE_METHODS: &[&str] = &[
"get",
"getByName",
"idFromName",
"idFromString",
"newUniqueId",
"jurisdiction",
];
/// `member` is a method of `DurableObjectNamespace`.
fn is_namespace_method(member: &str) -> bool {
NAMESPACE_METHODS.contains(&member)
}
/// The receiver of `<receiver>.<method>(...)`, when `method` is one of
/// `methods`.
fn method_call_receiver<'b, 'a>(
expr: &'b Expression<'a>,
methods: &[&str],
) -> Option<&'b Expression<'a>> {
let Expression::CallExpression(call) = unwrap_static_expr(expr) else {
return None;
};
call_method_receiver(call, methods)
}
/// The receiver of the call `<receiver>.<method>(...)`, when `method` is one
/// of `methods`.
fn call_method_receiver<'b, 'a>(
call: &'b CallExpression<'a>,
methods: &[&str],
) -> Option<&'b Expression<'a>> {
let Expression::StaticMemberExpression(member) = &call.callee else {
return None;
};
methods
.contains(&member.property.name.as_str())
.then_some(&member.object)
}
/// The namespace receiver of `<ns>.idFromName(...)`, `<ns>.idFromString(...)`
/// or `<ns>.newUniqueId()`.
fn durable_object_id_namespace<'b, 'a>(expr: &'b Expression<'a>) -> Option<&'b Expression<'a>> {
method_call_receiver(expr, ID_FACTORY_METHODS)
}
/// The id argument of a stub-making call.
enum StubId<'b, 'a> {
/// `getByName(name)` takes a name, not an id.
None,
/// `get(<ns>.idFromName(...))`: the namespace receiver of the inline id.
Inline(&'b Expression<'a>),
/// `get(id)`: the local that must hold an id of the same namespace.
Local(&'b str),
}
/// The namespace receiver and the id argument of `<ns>.getByName(...)` or
/// `<ns>.get(<id>)`.
fn durable_object_stub_call<'b, 'a>(
expr: &'b Expression<'a>,
) -> Option<(&'b Expression<'a>, StubId<'b, 'a>)> {
let Expression::CallExpression(call) = unwrap_static_expr(expr) else {
return None;
};
durable_object_stub_call_parts(call)
}
fn durable_object_stub_call_parts<'b, 'a>(
call: &'b CallExpression<'a>,
) -> Option<(&'b Expression<'a>, StubId<'b, 'a>)> {
if let Some(namespace) = call_method_receiver(call, &["getByName"]) {
return Some((namespace, StubId::None));
}
let namespace = call_method_receiver(call, &["get"])?;
let id = match call.arguments.first()?.as_expression()? {
Expression::Identifier(local) => StubId::Local(local.name.as_str()),
inline => StubId::Inline(durable_object_id_namespace(inline)?),
};
Some((namespace, id))
}
impl StructuralParamMemberCollector {
/// `const stub = env.NS.get(env.NS.idFromName(n))` makes `stub` an alias
/// of the namespace path `NS` of the tracked parameter `env`. Records an
/// id local (`const id = env.NS.idFromName(n)`) for a later `get(id)`.
pub(super) fn durable_object_stub_alias(
&mut self,
declarator: &VariableDeclarator<'_>,
) -> Option<(String, ReceiverAlias)> {
let BindingPattern::BindingIdentifier(local) = &declarator.id else {
return None;
};
let init = declarator.init.as_ref()?;
if let Some(namespace) = durable_object_id_namespace(init)
.and_then(|namespace| self.resolve_receiver_path(namespace, false))
{
self.durable_objects
.ids
.insert(local.name.to_string(), namespace);
return None;
}
let (namespace, id) = durable_object_stub_call(init)?;
let (namespace, _) = self.stub_namespace(namespace, &id)?;
let alias = ReceiverAlias {
target: namespace,
stub: true,
alternatives: Vec::new(),
};
Some((local.name.to_string(), alias))
}
/// `env.NS.get(env.NS.idFromName(n))`, or `env.NS.get(id)` with an id
/// local of `env.NS`, proves that `env.NS` is a namespace.
pub(super) fn record_durable_object_namespace(&mut self, call: &CallExpression<'_>) {
if let Some((namespace, id)) = durable_object_stub_call_parts(call)
&& let Some((namespace, true)) = self.stub_namespace(namespace, &id)
{
self.durable_objects.namespaces.insert(namespace);
}
}
/// The parameter and the namespace path of a stub-making call, and
/// whether its id argument comes from the same namespace. `None` when the
/// id comes from another receiver.
fn stub_namespace(
&self,
namespace: &Expression<'_>,
id: &StubId<'_, '_>,
) -> Option<((String, String), bool)> {
let namespace = self.resolve_receiver_path(namespace, false)?;
let id_namespace = match id {
StubId::None => return Some((namespace, false)),
StubId::Inline(id_namespace) => self.resolve_receiver_path(id_namespace, false),
StubId::Local(id_local) => self.durable_objects.ids.get(*id_local).cloned(),
};
(id_namespace.as_ref() == Some(&namespace)).then_some((namespace, true))
}
/// The namespace receiver of an inline stub call, such as
/// `env.NS.getByName(name)` in `env.NS.getByName(name).method()`.
pub(super) fn inline_stub_receiver(&self, object: &Expression<'_>) -> Option<ResolvedReceiver> {
let (namespace, id) = durable_object_stub_call(object)?;
let ((param, path), _) = self.stub_namespace(namespace, &id)?;
Some(ResolvedReceiver {
param,
path,
via_stub: true,
})
}
/// Records the access of `member` on `receiver`.
pub(super) fn record_member_access(&mut self, receiver: ResolvedReceiver, member: String) {
if !receiver.via_stub && is_namespace_method(&member) {
self.durable_objects
.method_accesses
.push((receiver.param, receiver.path, member));
return;
}
self.insert_member_access(receiver.param, receiver.path, member);
}
fn insert_member_access(&mut self, param: String, path: String, member: String) {
if path.is_empty() {
self.members.entry(param).or_default().insert(member);
} else {
self.property_members
.entry(param)
.or_default()
.insert((path, member));
}
}
/// A namespace method call (`env.NS.get(...)`) runs the namespace API, not
/// the method of the Durable Object class. Drops each such access on a
/// proven namespace path, and keeps the others.
pub(super) fn commit_namespace_method_accesses(&mut self) {
for (param, path, member) in std::mem::take(&mut self.durable_objects.method_accesses) {
if !self
.durable_objects
.namespaces
.contains(&(param.clone(), path.clone()))
{
self.insert_member_access(param, path, member);
}
}
}
}