Skip to content

Commit

Permalink
refactor: remove contracts snapshot from caches
Browse files Browse the repository at this point in the history
  • Loading branch information
eseidel committed Feb 20, 2024
1 parent 274f5d0 commit cfa2f1b
Show file tree
Hide file tree
Showing 9 changed files with 54 additions and 36 deletions.
23 changes: 9 additions & 14 deletions packages/cli/lib/behavior/trader.dart
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ Future<JobResult> _handleContractDealAtDestination(
const Duration(minutes: 10),
);
final contract = assertNotNull(
caches.contracts.contract(contractId),
await db.contractById(contractId),
'No contract.',
const Duration(minutes: 10),
);
Expand All @@ -255,7 +255,6 @@ Future<JobResult> _handleContractDealAtDestination(
api,
db,
caches.agent,
caches.contracts,
caches.ships,
ship,
contract,
Expand Down Expand Up @@ -308,7 +307,6 @@ Future<Contract?> _deliverContractGoodsIfPossible(
Api api,
Database db,
AgentCache agentCache,
ContractSnapshot contractSnapshot,
ShipSnapshot shipCache,
Ship ship,
Contract beforeDelivery,
Expand Down Expand Up @@ -339,7 +337,6 @@ Future<Contract?> _deliverContractGoodsIfPossible(
await acceptContractAndLog(
api,
db,
contractSnapshot,
agentCache,
ship,
beforeDelivery,
Expand All @@ -352,7 +349,6 @@ Future<Contract?> _deliverContractGoodsIfPossible(
api,
ship,
shipCache,
contractSnapshot,
beforeDelivery,
tradeSymbol: tradeSymbol,
units: unitsBefore,
Expand Down Expand Up @@ -557,30 +553,28 @@ String describeExpectedContractProfit(
Future<DateTime?> acceptContractsIfNeeded(
Api api,
Database db,
ContractSnapshot contractSnapshot,
MarketPriceSnapshot marketPrices,
AgentCache agentCache,
ShipSnapshot shipCache,
Ship ship,
) async {
/// Accept logic we run any time contract trading is turned on.
final contracts = contractSnapshot.activeContracts;
if (contracts.isEmpty) {
final activeContracts = await db.activeContracts();
if (activeContracts.isEmpty) {
final contract = await negotiateContractAndLog(
db,
api,
ship,
shipCache,
contractSnapshot,
);
shipInfo(ship, describeExpectedContractProfit(marketPrices, contract));
return null;
}
for (final contract in contractSnapshot.unacceptedContracts) {
final unacceptedContracts = await db.unacceptedContracts();
for (final contract in unacceptedContracts) {
await acceptContractAndLog(
api,
db,
contractSnapshot,
agentCache,
ship,
contract,
Expand Down Expand Up @@ -883,18 +877,19 @@ Future<JobResult> _initDeal(
await acceptContractsIfNeeded(
api,
db,
caches.contracts,
caches.marketPrices,
caches.agent,
caches.ships,
ship,
);
}

final contractSnapshot = await ContractSnapshot.load(db);

// Consider all deals starting at any market within our consideration range.
var newDeal = centralCommand.findNextDealAndLog(
caches.agent,
caches.contracts,
contractSnapshot,
caches.marketPrices,
caches.systems,
caches.systemConnectivity,
Expand Down Expand Up @@ -928,7 +923,7 @@ Future<JobResult> _initDeal(
findDeal: (Ship ship, WaypointSymbol startSymbol) {
return centralCommand.findNextDealAndLog(
caches.agent,
caches.contracts,
contractSnapshot,
caches.marketPrices,
caches.systems,
caches.systemConnectivity,
Expand Down
9 changes: 2 additions & 7 deletions packages/cli/lib/cache/caches.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ class Caches {
required this.systems,
required this.waypoints,
required this.markets,
required this.contracts,
required this.behaviors,
required this.charting,
required this.routePlanner,
Expand All @@ -78,9 +77,6 @@ class Caches {
// TODO(eseidel): Try not caching ships and just fetching from db.
ShipSnapshot ships;

/// The contract cache.
ContractSnapshot contracts;

/// Known shipyard listings.
ShipyardListingSnapshot shipyardListings;

Expand Down Expand Up @@ -148,7 +144,7 @@ class Caches {
);
final markets = MarketCache(db, api, static.tradeGoods);
// Intentionally force refresh contracts in case we've been offline.
final contracts = await fetchContracts(db, api);
await fetchContracts(db, api);
final behaviors = await BehaviorCache.load(db);

final jumpGates = await JumpGateSnapshot.load(db);
Expand All @@ -171,7 +167,6 @@ class Caches {
systems: systems,
waypoints: waypoints,
markets: markets,
contracts: contracts,
behaviors: behaviors,
charting: charting,
static: static,
Expand Down Expand Up @@ -208,7 +203,7 @@ class Caches {
// to run and update the status.
ships = await ships.ensureUpToDate(db, api);
await agent.ensureAgentUpToDate(api);
contracts = await contracts.ensureUpToDate(db, api);
await fetchContracts(db, api);

marketListings = await MarketListingSnapshot.load(db);
shipyardListings = await ShipyardListingSnapshot.load(db);
Expand Down
2 changes: 0 additions & 2 deletions packages/cli/lib/net/actions.dart
Original file line number Diff line number Diff line change
Expand Up @@ -578,7 +578,6 @@ Future<Contract> negotiateContractAndLog(
Api api,
Ship ship,
ShipSnapshot shipCache,
ContractSnapshot contractSnapshot,
) async {
await dockIfNeeded(db, api, shipCache, ship);
final response = await api.fleet.negotiateContract(ship.symbol);
Expand All @@ -594,7 +593,6 @@ Future<Contract> negotiateContractAndLog(
Future<AcceptContract200ResponseData> acceptContractAndLog(
Api api,
Database db,
ContractSnapshot contractSnapshot,
AgentCache agentCache,
Ship ship,
Contract contract,
Expand Down
2 changes: 0 additions & 2 deletions packages/cli/lib/net/direct.dart
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import 'package:cli/api.dart';
import 'package:cli/cache/agent_cache.dart';
import 'package:cli/cache/construction_cache.dart';
import 'package:cli/cache/contract_snapshot.dart';
import 'package:cli/cache/ship_cache.dart';
import 'package:db/db.dart';
import 'package:types/types.dart';
Expand Down Expand Up @@ -124,7 +123,6 @@ Future<DeliverContract200ResponseData> deliverContract(
Api api,
Ship ship,
ShipSnapshot shipCache,
ContractSnapshot contractSnapshot,
Contract contract, {
required TradeSymbol tradeSymbol,
required int units,
Expand Down
14 changes: 10 additions & 4 deletions packages/cli/test/behavior/trader_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ class _MockCentralCommand extends Mock implements CentralCommand {}

class _MockContractsApi extends Mock implements ContractsApi {}

class _MockContractSnapshot extends Mock implements ContractSnapshot {}

class _MockDatabase extends Mock implements Database {}

class _MockFleetApi extends Mock implements FleetApi {}
Expand Down Expand Up @@ -56,6 +58,8 @@ void main() {
when(() => centralCommand.isContractTradingEnabled).thenReturn(false);
when(() => centralCommand.expectedCreditsPerSecond(ship)).thenReturn(10);
final caches = mockCaches();
final contractSnapshot = _MockContractSnapshot();
when(db.allContracts).thenAnswer((_) async => <Contract>[]);

final start = WaypointSymbol.fromString('S-A-B');
final end = WaypointSymbol.fromString('S-A-C');
Expand Down Expand Up @@ -131,7 +135,7 @@ void main() {
when(
() => centralCommand.findNextDealAndLog(
caches.agent,
caches.contracts,
contractSnapshot,
caches.marketPrices,
caches.systems,
caches.systemConnectivity,
Expand Down Expand Up @@ -513,7 +517,7 @@ void main() {
when(() => centralCommand.isContractTradingEnabled).thenReturn(true);
when(() => centralCommand.expectedCreditsPerSecond(ship)).thenReturn(1);
final caches = mockCaches();
when(() => caches.contracts.activeContracts).thenReturn([]);
when(db.activeContracts).thenAnswer((_) async => <Contract>[]);
final contract = Contract(
id: 'id',
factionSymbol: 'factionSymbol',
Expand Down Expand Up @@ -622,10 +626,11 @@ void main() {
costPerFuelUnit: 100,
costPerAntimatterUnit: 10000,
);
final contractSnapshot = _MockContractSnapshot();
when(
() => centralCommand.findNextDealAndLog(
caches.agent,
caches.contracts,
contractSnapshot,
caches.marketPrices,
caches.systems,
caches.systemConnectivity,
Expand Down Expand Up @@ -694,6 +699,7 @@ void main() {

registerFallbackValue(Contract.fallbackValue());
when(() => db.upsertContract(any())).thenAnswer((_) async {});
when(db.allContracts).thenAnswer((_) async => <Contract>[]);

final logger = _MockLogger();
final waitUntil = await runWithLogger(
Expand Down Expand Up @@ -1086,7 +1092,7 @@ void main() {
fulfilled: false,
timestamp: now,
);
when(() => caches.contracts.contract(contract.id)).thenReturn(contract);
when(() => db.contractById(contract.id)).thenAnswer((_) async => contract);
final deal = Deal(
destination: SellOpp.fromContract(
waypointSymbol: end,
Expand Down
3 changes: 0 additions & 3 deletions packages/cli/test/cache/caches_mock.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ class _MockChartingCache extends Mock implements ChartingCache {}

class _MockConstructionCache extends Mock implements ConstructionCache {}

class _MockContractSnapshot extends Mock implements ContractSnapshot {}

class _MockJumpGateSnapshot extends Mock implements JumpGateSnapshot {}

class _MockMarketCache extends Mock implements MarketCache {}
Expand Down Expand Up @@ -76,7 +74,6 @@ Caches mockCaches() {
waypoints: _MockWaypointCache(),
markets: _MockMarketCache(),
marketListings: _MockMarketListingSnapshot(),
contracts: _MockContractSnapshot(),
behaviors: _MockBehaviorCache(),
charting: _MockChartingCache(),
routePlanner: _MockRoutePlanner(),
Expand Down
4 changes: 0 additions & 4 deletions packages/cli/test/net/actions_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,6 @@ class _MockDatabase extends Mock implements Database {}

class _MockChartingCache extends Mock implements ChartingCache {}

class _MockContractSnapshot extends Mock implements ContractSnapshot {}

class _MockContractsApi extends Mock implements ContractsApi {}

class _MockFleetApi extends Mock implements FleetApi {}
Expand Down Expand Up @@ -787,7 +785,6 @@ void main() {
final shipNav = _MockShipNav();
when(() => ship.nav).thenReturn(shipNav);
when(() => shipNav.waypointSymbol).thenReturn('S-A-W');
final contractSnapshot = _MockContractSnapshot();
final contract = Contract.test(
id: 'C-1',
terms: ContractTerms(
Expand Down Expand Up @@ -823,7 +820,6 @@ void main() {
await acceptContractAndLog(
api,
db,
contractSnapshot,
agentCache,
ship,
contract,
Expand Down
13 changes: 13 additions & 0 deletions packages/db/lib/db.dart
Original file line number Diff line number Diff line change
Expand Up @@ -401,6 +401,19 @@ class Database {
return queryMany(allContractsQuery(), contractFromColumnMap);
}

Future<Contract?> contractById(String id) async {
final query = contractByIdQuery(id);
return queryOne(query, contractFromColumnMap);
}

Future<Iterable<Contract>> unacceptedContracts() async {
return queryMany(unacceptedContractsQuery(), contractFromColumnMap);
}

Future<Iterable<Contract>> activeContracts() async {
return queryMany(activeContractsQuery(), contractFromColumnMap);
}

/// Upsert a contract into the database.
Future<void> upsertContract(Contract contract) async {
await execute(upsertContractQuery(contract));
Expand Down
20 changes: 20 additions & 0 deletions packages/db/lib/src/contract.dart
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,26 @@ Query upsertContractQuery(Contract contract) {
);
}

/// Fetch a contract by id.
Query contractByIdQuery(String id) {
return Query(
'SELECT * FROM contract_ WHERE id = @id',
parameters: <String, dynamic>{'id': id},
);
}

Query activeContractsQuery() {
return const Query(
"SELECT * FROM contract_ WHERE json->>'status' = 'active'",
);
}

Query unacceptedContractsQuery() {
return const Query(
"SELECT * FROM contract_ WHERE json->>'status' = 'unaccepted'",
);
}

/// Converts a contract from a column map.
Contract contractFromColumnMap(Map<String, dynamic> map) {
return Contract.fromJson(map['json'] as Map<String, dynamic>);
Expand Down

0 comments on commit cfa2f1b

Please sign in to comment.