-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.rs
398 lines (352 loc) · 11.2 KB
/
main.rs
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
use async_graphql::http::GraphiQLSource;
use dotenv::dotenv;
use rocket::response::content::RawHtml;
use std::env;
use std::ops::Deref;
use std::vec;
use async_graphql::*;
use async_graphql_rocket::GraphQLRequest as Request;
use async_graphql_rocket::GraphQLResponse as Response;
use rocket::State;
struct QueryRoot;
#[derive(Clone, SimpleObject)]
pub struct Ship {
id: ID,
fuel: i32,
position: Position,
shipyard_policy: PolicyId,
ship_token_name: AssetName,
pilot_token_name: AssetName,
class: String,
}
#[derive(Clone, SimpleObject)]
pub struct FuelPellet {
id: ID,
fuel: i32,
position: Position,
shipyard_policy: PolicyId,
class: String,
}
#[derive(Clone, SimpleObject)]
pub struct RewardPot {
id: ID,
position: Position,
total_rewards: i32,
class: String,
}
#[derive(Clone, SimpleObject)]
pub struct AsteriaState {
ship_counter: i32,
shipyard_policy: PolicyId,
}
#[derive(Clone, SimpleObject)]
pub struct Position {
x: i32,
y: i32,
}
#[derive(Clone, SimpleObject)]
pub struct PolicyId {
id: ID,
}
#[derive(Clone, SimpleObject)]
pub struct AssetName {
name: String,
}
#[derive(InputObject)]
pub struct AssetNameInput {
name: String,
}
#[derive(InputObject, Clone, Copy)]
pub struct PositionInput {
x: i32,
y: i32,
}
#[derive(SimpleObject, Clone)]
pub struct ShipAction {
action_id: ID,
ship_id: ID,
action_type: ShipActionType,
position: Position,
timestamp: String,
}
#[derive(Enum, Copy, Clone, Eq, PartialEq)]
pub enum ShipActionType {
Move,
GatherFuel,
}
#[derive(Union)]
pub enum MapObject {
Ship(Ship),
FuelPellet(FuelPellet),
RewardPot(RewardPot),
}
#[derive(Interface)]
#[graphql(
field(name = "position", ty = "&Position"),
field(name = "class", ty = "String")
)]
pub enum PositionalInterface {
Ship(Ship),
FuelPellet(FuelPellet),
RewardPot(RewardPot),
}
struct MapObjectRecord {
id: String,
fuel: Option<i32>,
position_x: i32,
position_y: i32,
policy_id: Option<String>,
token_name: Option<String>,
pilot_name: Option<String>,
class: Option<String>,
total_rewards: Option<i32>,
}
#[Object]
impl QueryRoot {
async fn ship(&self, _ctx: &Context<'_>, ship_token_name: AssetNameInput) -> Ship {
Ship {
id: ID::from("ship-1234"),
fuel: 100,
position: Position { x: 10, y: 20 },
shipyard_policy: PolicyId {
id: ID::from("policy-5678"),
},
ship_token_name: AssetName {
name: ship_token_name.name.clone(),
},
pilot_token_name: AssetName {
name: "PilotOne".to_string(),
},
class: "Ship".to_string(),
}
}
async fn ships(
&self,
_ctx: &Context<'_>,
limit: Option<i32>,
offset: Option<i32>,
) -> Vec<Ship> {
let mut ships = Vec::new();
let num_ships = limit.unwrap_or(10);
let start = offset.unwrap_or(0) as usize;
// Generate fake data for ships
for i in start..(start + num_ships as usize) {
ships.push(Ship {
id: ID::from(format!("ship-{}", i)),
fuel: 100,
position: Position {
x: i as i32 * 10,
y: i as i32 * 20,
},
shipyard_policy: PolicyId {
id: ID::from(format!("policy-{}", i)),
},
ship_token_name: AssetName {
name: format!("Explorer-{}", i),
},
pilot_token_name: AssetName {
name: format!("Pilot-{}", i),
},
class: "Battleship".to_string(),
});
}
ships
}
async fn fuel_pellets(
&self,
_ctx: &Context<'_>,
limit: Option<i32>,
offset: Option<i32>,
) -> Vec<FuelPellet> {
let mut fuel_pellets = Vec::new();
let num_pellets = limit.unwrap_or(10);
let start = offset.unwrap_or(0) as usize;
// Generate fake data for fuel pellets
for i in start..(start + num_pellets as usize) {
fuel_pellets.push(FuelPellet {
id: ID::from(format!("pellet-{}", i)),
fuel: 100,
position: Position {
x: i as i32 * 5,
y: i as i32 * 10,
},
shipyard_policy: PolicyId {
id: ID::from(format!("policy-{}", i)),
},
class: "Standard".to_string(),
});
}
fuel_pellets
}
async fn asteria_state(&self, _ctx: &Context<'_>) -> AsteriaState {
AsteriaState {
ship_counter: 123,
shipyard_policy: PolicyId {
id: ID::from("some-policy-id"),
},
}
}
async fn reward_pot(&self, _ctx: &Context<'_>) -> RewardPot {
RewardPot {
id: ID::from("reward-123"),
position: Position { x: 100, y: 200 },
total_rewards: 5000,
class: "Standard".to_string(),
}
}
async fn objects_in_radius(
&self,
ctx: &Context<'_>,
center: PositionInput,
radius: i32,
) -> Result<Vec<MapObject>, Error> {
// Access the connection pool from the GraphQL context
let pool = ctx
.data::<sqlx::PgPool>()
.map_err(|e| Error::new(e.message))?;
// Query to select map objects within a radius using Manhattan distance
let fetched_objects = sqlx::query_as!(MapObjectRecord,
"SELECT id, fuel, positionX as position_x, positionY as position_y, shipyardPolicy as policy_id, shipTokenName as token_name, pilotTokenName as pilot_name, class, totalRewards as total_rewards
FROM MapObjects
WHERE positionX BETWEEN ($1::int - $3::int) AND ($1::int + $3::int)
AND positionY BETWEEN ($2::int - $3::int) AND ($2::int + $3::int)
AND ABS(positionX - $1::int) + ABS(positionY - $2::int) <= $3::int",
center.x, center.y, radius
)
.fetch_all(pool)
.await
.map_err(|e| Error::new(e.to_string()))?;
let map_objects: Vec<MapObject> = fetched_objects
.into_iter()
.map(|record| match record.class.as_deref() {
Some("Ship") => MapObject::Ship(Ship {
id: ID::from(record.id),
fuel: record.fuel.unwrap_or(0),
position: Position {
x: record.position_x,
y: record.position_y,
},
shipyard_policy: PolicyId {
id: ID::from(record.policy_id.unwrap_or_default()),
},
ship_token_name: AssetName {
name: record.token_name.unwrap_or_default(),
},
pilot_token_name: AssetName {
name: record.pilot_name.unwrap_or_default(),
},
class: record.class.unwrap_or_default(),
}),
Some("FuelPellet") => MapObject::FuelPellet(FuelPellet {
id: ID::from(record.id),
fuel: record.fuel.unwrap_or(0),
position: Position {
x: record.position_x,
y: record.position_y,
},
shipyard_policy: PolicyId {
id: ID::from(record.policy_id.unwrap_or_default()),
},
class: record.class.unwrap_or_default(),
}),
Some("RewardPot") => MapObject::RewardPot(RewardPot {
id: ID::from(record.id),
position: Position {
x: record.position_x,
y: record.position_y,
},
total_rewards: record.total_rewards.unwrap_or(0),
class: record.class.unwrap_or_default(),
}),
_ => panic!("Unknown class type or class not provided"),
})
.collect();
Ok(map_objects)
}
async fn all_ship_actions(
&self,
_ctx: &Context<'_>,
limit: Option<i32>,
offset: Option<i32>,
) -> Vec<ShipAction> {
let mut actions = Vec::new();
let num_actions = limit.unwrap_or(10) as usize;
let start = offset.unwrap_or(0) as usize;
// Generate fake data for ship actions
for i in start..(start + num_actions) {
actions.push(ShipAction {
action_id: ID::from(format!("action-{}", i)),
ship_id: ID::from("ship-1"),
action_type: ShipActionType::Move,
position: Position {
x: i as i32 * 5,
y: i as i32 * 10,
},
timestamp: "01/01/1971".to_string(),
});
}
actions
}
async fn ship_actions(
&self,
_ctx: &Context<'_>,
ship_id: ID,
limit: Option<i32>,
offset: Option<i32>,
) -> Vec<ShipAction> {
let mut actions = Vec::new();
let num_actions = limit.unwrap_or(5) as usize;
let start = offset.unwrap_or(0) as usize;
// Generate fake data for specific ship actions
for i in start..(start + num_actions) {
actions.push(ShipAction {
action_id: ID::from(format!("action-{}-{}", *ship_id, i)),
ship_id: ship_id.clone(),
action_type: if i % 2 == 0 {
ShipActionType::Move
} else {
ShipActionType::GatherFuel
},
position: Position {
x: 100 + i as i32,
y: 200 + i as i32,
},
timestamp: "01/01/1971".to_string(),
});
}
actions
}
}
type AsteriaSchema = Schema<QueryRoot, EmptyMutation, EmptySubscription>;
#[macro_use]
extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, world!"
}
#[rocket::post("/graphql", data = "<request>", format = "application/json")]
async fn graphql_request(schema: &State<AsteriaSchema>, request: Request) -> Response {
request.execute(schema.deref()).await
}
#[rocket::get("/graphql")]
async fn graphiql() -> RawHtml<String> {
rocket::response::content::RawHtml(GraphiQLSource::build().endpoint("/graphql").finish())
}
#[launch]
async fn rocket() -> _ {
dotenv().ok();
let database_url =
env::var("DATABASE_URL").expect("DATABASE_URL must be set in the environment");
let pool = sqlx::postgres::PgPoolOptions::new()
.max_connections(5)
.connect(database_url.as_str())
.await
.expect("Failed to create pool");
let schema = Schema::build(QueryRoot, EmptyMutation, EmptySubscription)
.register_output_type::<PositionalInterface>()
.data(pool.clone())
.finish();
rocket::build()
.manage(schema)
.mount("/", routes![index, graphql_request, graphiql])
}