-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathget_record.rs
More file actions
275 lines (247 loc) · 8.43 KB
/
Copy pathget_record.rs
File metadata and controls
275 lines (247 loc) · 8.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
//! com.atproto.repo.getRecord endpoint.
//!
//! Retrieves a single record from a repository.
use std::net::SocketAddr;
use std::sync::Arc;
use axum::{
Json,
extract::{ConnectInfo, Query, State},
http::{HeaderMap, StatusCode},
response::{IntoResponse, Response},
};
use serde::{Deserialize, Serialize};
use crate::pds::db::StatisticKey;
use crate::pds::server::PdsState;
use super::{get_caller_info};
use crate::repo::DagCborObject;
use crate::ws::{ActorQueryOptions, BlueskyClient, DEFAULT_APP_VIEW_HOST_NAME};
use urlencoding::encode;
/// Query parameters for getRecord.
#[derive(Deserialize)]
pub struct GetRecordQuery {
/// Repository DID or handle.
repo: Option<String>,
/// Collection NSID.
collection: Option<String>,
/// Record key.
rkey: Option<String>,
/// Optional CID to verify record version.
cid: Option<String>,
}
/// Successful response for getRecord.
#[derive(Serialize)]
pub struct GetRecordResponse {
/// AT URI of the record.
uri: String,
/// CID of the record.
cid: String,
/// The record data.
value: serde_json::Value,
}
/// Error response for getRecord.
#[derive(Serialize)]
pub struct GetRecordError {
error: String,
message: String,
}
/// GET /xrpc/com.atproto.repo.getRecord - Get a single record.
///
/// Retrieves a single record from a repository by collection and rkey.
///
/// # Query Parameters
///
/// * `repo` - Repository identifier (DID or handle)
/// * `collection` - Collection NSID
/// * `rkey` - Record key
/// * `cid` - Optional CID to verify record version
///
/// # Returns
///
/// * `200 OK` with the record
/// * `400 Bad Request` if parameters are invalid
/// * `404 Not Found` if the record doesn't exist
pub async fn get_record(
State(state): State<Arc<PdsState>>,
ConnectInfo(addr): ConnectInfo<SocketAddr>,
headers: HeaderMap,
Query(query): Query<GetRecordQuery>,
) -> Response {
// Get caller info for statistics
let (ip_address, user_agent) = get_caller_info(&headers, Some(addr));
// Increment statistics
let stat_key = StatisticKey {
name: "xrpc/com.atproto.repo.getRecord".to_string(),
ip_address,
user_agent,
};
let _ = state.db.increment_statistic_for_endpoint(&stat_key);
// Validate required parameters
let collection = match &query.collection {
Some(c) if !c.is_empty() => c,
_ => {
return (
StatusCode::BAD_REQUEST,
Json(GetRecordError {
error: "InvalidRequest".to_string(),
message: "Error: Params must have 'collection' and 'rkey'.".to_string(),
}),
)
.into_response();
}
};
let rkey = match &query.rkey {
Some(r) if !r.is_empty() => r,
_ => {
return (
StatusCode::BAD_REQUEST,
Json(GetRecordError {
error: "InvalidRequest".to_string(),
message: "Error: Params must have 'collection' and 'rkey'.".to_string(),
}),
)
.into_response();
}
};
// Get local user info
let user_did = state.db.get_config_property("UserDid").unwrap_or_default();
let user_handle = state.db.get_config_property("UserHandle").unwrap_or_default();
// Determine the repo to query
let repo = query.repo.as_deref().unwrap_or(&user_did);
// Check if this is a local repo request
let is_local = repo == user_did || repo == user_handle;
if !is_local {
// Proxy request to the AppView
state.log.info(&format!("Proxying getRecord request for repo: {}", repo));
let app_view_host_name = state.db.get_config_property("AppViewHostName")
.unwrap_or_else(|_| DEFAULT_APP_VIEW_HOST_NAME.to_string());
let client = BlueskyClient::new(&app_view_host_name);
let options = ActorQueryOptions {
resolve_handle_via_bluesky: true,
..Default::default()
};
let actor_info = match client.resolve_actor_info(repo, Some(options)).await {
Ok(info) => info,
Err(e) => {
state.log.error(&format!("Unable to resolve actor info for repo: {}: {}", repo, e));
return (
StatusCode::NOT_FOUND,
Json(GetRecordError {
error: "NotFound".to_string(),
message: "Unable to resolve repository".to_string(),
}),
)
.into_response();
}
};
let actor_did = actor_info.did.unwrap_or_default();
// Make proxy request to AppView
let target_url = format!(
"https://{}/xrpc/com.atproto.repo.getRecord?repo={}&collection={}&rkey={}",
app_view_host_name, encode(&actor_did), encode(collection), encode(rkey)
);
state.log.info(&format!("Proxying to: {}", target_url));
let http_client = reqwest::Client::new();
match http_client.get(&target_url).send().await {
Ok(response) => {
if response.status().is_success() {
match response.json::<serde_json::Value>().await {
Ok(json) => {
return (StatusCode::OK, Json(json)).into_response();
}
Err(e) => {
state.log.error(&format!("Error parsing proxy response: {}", e));
}
}
}
}
Err(e) => {
state.log.error(&format!("Error proxying getRecord request: {}", e));
}
}
return (
StatusCode::NOT_FOUND,
Json(GetRecordError {
error: "NotFound".to_string(),
message: "Record not found".to_string(),
}),
)
.into_response();
}
// Local record retrieval
let record_exists = match state.db.record_exists(collection, rkey) {
Ok(exists) => exists,
Err(e) => {
state.log.error(&format!("Database error checking record: {}", e));
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(GetRecordError {
error: "InternalError".to_string(),
message: "Database error".to_string(),
}),
)
.into_response();
}
};
if !record_exists {
return (
StatusCode::NOT_FOUND,
Json(GetRecordError {
error: "NotFound".to_string(),
message: "Error: Record not found.".to_string(),
}),
)
.into_response();
}
let repo_record = match state.db.get_repo_record(collection, rkey) {
Ok(record) => record,
Err(e) => {
state.log.error(&format!("Failed to get record: {}", e));
return (
StatusCode::NOT_FOUND,
Json(GetRecordError {
error: "NotFound".to_string(),
message: "Error: Record not found.".to_string(),
}),
)
.into_response();
}
};
// Verify CID if provided
if let Some(expected_cid) = &query.cid {
if &repo_record.cid != expected_cid {
return (
StatusCode::NOT_FOUND,
Json(GetRecordError {
error: "NotFound".to_string(),
message: "Record CID mismatch".to_string(),
}),
)
.into_response();
}
}
// Parse the DAG-CBOR data to JSON
let value = match DagCborObject::from_bytes(&repo_record.dag_cbor_bytes) {
Ok(dag_cbor) => dag_cbor.to_json_value(),
Err(e) => {
state.log.error(&format!("Failed to parse record data: {}", e));
return (
StatusCode::INTERNAL_SERVER_ERROR,
Json(GetRecordError {
error: "InternalError".to_string(),
message: "Failed to parse record data".to_string(),
}),
)
.into_response();
}
};
let uri = format!("at://{}/{}/{}", user_did, collection, rkey);
(
StatusCode::OK,
Json(GetRecordResponse {
uri,
cid: repo_record.cid,
value,
}),
)
.into_response()
}