From d668eac4a63a9aa98c3efff395faa23cfcea1c1b Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Thu, 21 Mar 2024 17:08:37 +0100 Subject: [node] begin the great typescript rewrite --- nodejs/lib/api.js | 163 ---------------------------------- nodejs/lib/api.ts | 160 +++++++++++++++++++++++++++++++++ nodejs/lib/contracts.js | 68 --------------- nodejs/lib/contracts.ts | 74 ++++++++++++++++ nodejs/lib/priority_queue.js | 39 --------- nodejs/lib/priority_queue.ts | 36 ++++++++ nodejs/lib/ships.js | 195 ----------------------------------------- nodejs/lib/ships.ts | 204 +++++++++++++++++++++++++++++++++++++++++++ nodejs/lib/systems.js | 86 ------------------ nodejs/lib/systems.ts | 86 ++++++++++++++++++ nodejs/lib/utils.js | 18 ---- nodejs/lib/utils.ts | 25 ++++++ 12 files changed, 585 insertions(+), 569 deletions(-) delete mode 100644 nodejs/lib/api.js create mode 100644 nodejs/lib/api.ts delete mode 100644 nodejs/lib/contracts.js create mode 100644 nodejs/lib/contracts.ts delete mode 100644 nodejs/lib/priority_queue.js create mode 100644 nodejs/lib/priority_queue.ts delete mode 100644 nodejs/lib/ships.js create mode 100644 nodejs/lib/ships.ts delete mode 100644 nodejs/lib/systems.js create mode 100644 nodejs/lib/systems.ts delete mode 100644 nodejs/lib/utils.js create mode 100644 nodejs/lib/utils.ts (limited to 'nodejs/lib') diff --git a/nodejs/lib/api.js b/nodejs/lib/api.js deleted file mode 100644 index ecb0282..0000000 --- a/nodejs/lib/api.js +++ /dev/null @@ -1,163 +0,0 @@ -import * as fs from 'fs'; -import * as events from 'events'; - -import { getToken } from '../database/tokens.js'; -import { PriorityQueue } from './priority_queue.js'; - -// queue processor module variables -const bus = new events.EventEmitter(); // a bus to notify the queue processor to start processing messages -let busy = false; // true if we are already sending api requests. -let backoffSeconds = 0; -let running = false; -// other module variables -let headers = undefined; // a file scoped variable so that we only evaluate these once. -let queue = new PriorityQueue(); // a priority queue to hold api calls we want to send, allows for throttling. - -// a single queue processor should be running at any time, otherwise there will be trouble! -async function queue_processor() { - if (running) { - throw 'refusing to start a second queue processor'; - } - running = true; - while(true) { - try { - if (backoffSeconds > 0) { - await sleep(backoffSeconds * 1000); - backoffSeconds = 0; - } - if (queue.isEmpty()) { - busy = false; - await new Promise(resolve => bus.once('send', resolve)); - busy = true; - } - const before = new Date(); - await send_this(queue.dequeue().element); - const duration = new Date() - before; - if (duration < 400) { // 333 should work, but 400 should still allow some manual requests to go through during development - await sleep(400 - duration); - } - } catch (e) { - running = false; - throw e; - } - } -} -queue_processor(); - -// send takes a request object as argument and an optional context ctx -// example request: { -// endpoint: the path part of the url to call, -// method: HTTP method for `fetch` call, defaults to 'GET', -// page: run a paginated request starting from this page until all the following pages are fetched -// payload: optional json object that will be send along with the request, -// priority: optional priority value (defaults to 10, lower than 10 means the message will be sent faster) -// } -export async function send(request, ctx) { - if (request.page === undefined) { - return await send_one(request, ctx); - } - let ret = []; - while (true) { - const response = await send_one(request, ctx); - if (response.meta === undefined) { - throw {"message": "paginated request did not return a meta block", "request": request, "response": response}; - } - ret = ret.concat(response.data); - if (response.meta.limit * response.meta.page >= response.meta.total) { - return ret; - } - request.page++; - } -} - -function send_one(request, ctx) { - return new Promise((resolve, reject) => { - let data = { - ctx: ctx, - reject: reject, - request: request, - resolve: resolve, - }; - queue.enqueue(data, request.priority ? request.priority : 10); - if (!busy) { - bus.emit('send'); // the queue was previously empty, let's wake up the queue_processor - } - }); -} - -// send_this take a data object as argument built in the send function above -async function send_this(data) { - if (headers === undefined) { - const token = getToken(); - if (token === null) { - throw 'Could not get token from the database. Did you init or register yet?'; - } - headers = { - 'Content-Type': 'application/json', - 'Authorization': `Bearer ${token}` - }; - } - let options = { - headers: headers, - }; - if (data.request.method !== undefined) { - options['method'] = data.request.method; - } - if (data.request.payload !== undefined) { - options['body'] = JSON.stringify(data.request.payload); - } - let pagination = ""; - if (data.request.page !== undefined) { - pagination=`?limit=20&page=${data.request.page}`; - } - fs.writeFileSync('log', JSON.stringify({event: 'send', date: new Date(), data: data}) + '\n', {flag: 'a+'}); - try { - let response = await fetch(`https://api.spacetraders.io/v2${data.request.endpoint}${pagination}`, options); - response = await response.json(); - switch(response.error?.code) { - case 401: // TODO 401 means a server reset happened - throw response; - // TODO reject all promises in queue - // reset database - // logrotate - // spawnSync? - // break; - case 429: // 429 means rate limited, let's hold back as instructed - backoffSeconds = response.error.data.retryAfter; - queue.enqueue(data, 1); - break; - case 503: // 503 means maintenance mode, let's hold back for 1 minute - backoffSeconds = 60; - queue.enqueue(data, 1); - break; - default: // no error! - fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: response}) + '\n', {flag: 'a+'}); - return data.resolve(response); - } - } catch (err) { - fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: err}) + '\n', {flag: 'a+'}); - switch(err.cause?.code) { - case 'EAI_AGAIN': // DNS lookup timed out error, let's hold back for 5 seconds - backoffSeconds = 5; - queue.enqueue(data, 1); - break; - case 'ECONNRESET': - queue.enqueue(data, 1); - break; - case 'UND_ERR_CONNECT_TIMEOUT': - queue.enqueue(data, 1); - break; - default: - data.reject(err); - } - } -} - -export function debugLog(ctx) { - console.log(`--- ${Date()} -----------------------------------------------------------------------------`); - console.log(JSON.stringify(ctx, null, 2)); -} - -export function sleep(delay) { - return new Promise((resolve) => setTimeout(resolve, delay)) -} diff --git a/nodejs/lib/api.ts b/nodejs/lib/api.ts new file mode 100644 index 0000000..08c6c71 --- /dev/null +++ b/nodejs/lib/api.ts @@ -0,0 +1,160 @@ +import * as fs from 'fs'; +import * as events from 'events'; + +import { APIError, Request, RequestPromise, Response } from '../model/api.ts'; +import { getToken } from '../database/tokens.ts'; +import { PriorityQueue } from './priority_queue.ts'; + +// queue processor module variables +const bus = new events.EventEmitter(); // a bus to notify the queue processor to start processing messages +let busy = false; // true if we are already sending api requests. +let backoffSeconds = 0; +let running = false; +// other module variables +let headers: {[key:string]:string}|null = null; // a file scoped variable so that we only evaluate these once. +let queue = new PriorityQueue(); // a priority queue to hold api calls we want to send, allows for throttling. + +async function queue_processor() { + if (running) { + throw 'refusing to start a second queue processor'; + } + running = true; + while(true) { + try { + if (backoffSeconds > 0) { + await sleep(backoffSeconds * 1000); + backoffSeconds = 0; + } + if (queue.isEmpty()) { + busy = false; + await new Promise(resolve => bus.once('send', resolve)); + busy = true; + } + const before = new Date().getTime(); + const data = queue.dequeue() as RequestPromise; + await send_this(data); + const duration = new Date().getTime() - before; + if (duration < 400) { // 333 should work, but 400 should still allow some manual requests to go through during development + await sleep(400 - duration); + } + } catch (e) { + running = false; + throw e; + } + } +} +queue_processor(); + +export async function send(request: Request): Promise { + const response = await send_one(request); + if (response.error) return response.error; + return response.data; +} + +export async function sendPaginated(request: Request): Promise|APIError> { + if (request.page === undefined) request.page = 1; + let ret: Array = []; + while (true) { + const response = await send_one(request); + if (response.meta === undefined) { + throw {"message": "paginated request did not return a meta block", "request": request, "response": response}; + } + ret = ret.concat(response.data); + if (response.meta.limit * response.meta.page >= response.meta.total) { + return ret; + } + request.page++; + } +} + +function send_one(request: Request): Promise> { + return new Promise((resolve, reject) => { + const data: RequestPromise = { + reject: reject, + request: request, + resolve: resolve, + }; + queue.enqueue(data, request.priority ? request.priority : 10); + if (!busy) { + bus.emit('send'); // the queue was previously empty, let's wake up the queue_processor + } + }); +} + +// send_this take a data object as argument built in the send function above +async function send_this(data: RequestPromise) { + if (headers === null) { + const token = getToken(); + if (token === null) { + throw 'Could not get token from the database. Did you init or register yet?'; + } + headers = { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${token}` + }; + } + let options: {[key:string]:any} = { + headers: headers, + }; + if (data.request.method !== undefined) { + options['method'] = data.request.method; + } + if (data.request.payload !== undefined) { + options['body'] = JSON.stringify(data.request.payload); + } + let pagination = ""; + if (data.request.page !== undefined) { + pagination=`?limit=20&page=${data.request.page}`; + } + fs.writeFileSync('log', JSON.stringify({event: 'send', date: new Date(), data: data}) + '\n', {flag: 'a+'}); + try { + const response = await fetch(`https://api.spacetraders.io/v2${data.request.endpoint}${pagination}`, options); + const json = await response.json() as Response; + switch(json.error?.code) { + case 401: // TODO 401 means a server reset happened + throw json; + // TODO reject all promises in queue + // reset database + // logrotate + // spawnSync? + // break; + case 429: // 429 means rate limited, let's hold back as instructed + backoffSeconds = json.error.data.retryAfter; + queue.enqueue(data, 1); + break; + case 503: // 503 means maintenance mode, let's hold back for 1 minute + backoffSeconds = 60; + queue.enqueue(data, 1); + break; + default: // no error! + fs.writeFileSync('log', JSON.stringify({event: 'response', date: new Date(), data: json}) + '\n', {flag: 'a+'}); + return data.resolve(json); + } + } catch (_err) { + const err = _err as {cause?: {code: string}}; + fs.writeFileSync('log', JSON.stringify({event: 'error', date: new Date(), data: err}) + '\n', {flag: 'a+'}); + switch(err.cause?.code) { + case 'EAI_AGAIN': // DNS lookup timed out error, let's hold back for 5 seconds + backoffSeconds = 5; + queue.enqueue(data, 1); + break; + case 'ECONNRESET': + queue.enqueue(data, 1); + break; + case 'UND_ERR_CONNECT_TIMEOUT': + queue.enqueue(data, 1); + break; + default: + data.reject(err); + } + } +} + +export function debugLog(ctx: any) { + console.log(`--- ${Date()} -----------------------------------------------------------------------------`); + console.log(JSON.stringify(ctx, null, 2)); +} + +export function sleep(delay: number): Promise { + return new Promise((resolve) => setTimeout(resolve, delay)); +} diff --git a/nodejs/lib/contracts.js b/nodejs/lib/contracts.js deleted file mode 100644 index 9718f99..0000000 --- a/nodejs/lib/contracts.js +++ /dev/null @@ -1,68 +0,0 @@ -import * as dbAgents from '../database/agents.js'; -import * as dbContracts from '../database/contracts.js'; -import * as api from './api.js'; -import * as dbShips from '../database/ships.js'; -import * as libShips from '../lib/ships.js'; - -export async function accept(ctx) { - const contract = dbContracts.getContract(ctx.id); - if (contract.accepted) { - return; - } - await api.send({endpoint: `/my/contracts/${ctx.id}/accept`, method: 'POST'}); - contract.accepted = true; - dbContracts.setContract(contract); -} - -export async function contracts() { - const contracts = await api.send({endpoint: '/my/contracts', page: 1}); - contracts.forEach(contract => dbContracts.setContract(contract)); - return contracts; -} - -// returns true if the contract has been fulfilled -export async function deliver(ctx) { - const contract = dbContracts.getContract(ctx.id); - if (contract.terms.deliver[0].unitsRequired === contract.terms.deliver[0].unitsFulfilled) { - await fulfill(ctx); - return true; - } - await libShips.dock(ctx); - const response = await api.send({ endpoint: `/my/contracts/${ctx.id}/deliver`, method: 'POST', payload: { - shipSymbol: ctx.symbol, - tradeSymbol: ctx.good, - units: ctx.units, - }}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4509: // contract delivery terms have been met - await fulfill(ctx); - return true; - default: // yet unhandled error - api.debugLog(response); - throw response; - } - } - dbContracts.setContract(response.data.contract); - dbShips.setShipCargo(ctx.symbol, response.data.cargo); - // TODO track credits - if(response.data.contract.terms.deliver[0].unitsRequired === response.data.contract.terms.deliver[0].unitsFulfilled) { - await fulfill(ctx); - return true; - } - return false; -} - -export async function fulfill(ctx) { - const contract = dbContracts.getContract(ctx.id); - if (contract.fulfilled) { - return; - } - const response = await api.send({ endpoint: `/my/contracts/${ctx.id}/fulfill`, method: 'POST'}); - if (response.error !== undefined) { - api.debugLog(response); - throw response; - } - dbAgents.setAgent(response.data.agent); - dbContracts.setContract(response.data.contract); -} diff --git a/nodejs/lib/contracts.ts b/nodejs/lib/contracts.ts new file mode 100644 index 0000000..fb62813 --- /dev/null +++ b/nodejs/lib/contracts.ts @@ -0,0 +1,74 @@ +import { Agent } from '../model/agent.ts'; +import { APIError } from '../model/api.ts'; +import { Cargo } from '../model/cargo.ts'; +import { Contract } from '../model/contract.ts'; +import { Ship } from '../model/ship.ts'; +import * as dbAgents from '../database/agents.ts'; +import * as dbContracts from '../database/contracts.ts'; +import * as api from './api.ts'; +import * as dbShips from '../database/ships.ts'; +import * as libShips from '../lib/ships.ts'; + +export async function accept(contract: Contract): Promise { + if (contract.accepted) return contract; + const response = await api.send<{agent: Agent, contract: Contract, type: ''}>({endpoint: `/my/contracts/${contract.id}/accept`, method: 'POST'}); + if ('apiError' in response) { + api.debugLog(response); + throw response; + } + dbAgents.setAgent(response.agent); + dbContracts.setContract(response.contract); + return response.contract; +} + +export async function contracts(): Promise> { + const response = await api.sendPaginated({endpoint: '/my/contracts', page: 1}); + if ('apiError' in response) { + api.debugLog(response); + throw response; + } + response.forEach(contract => dbContracts.setContract(contract)); + return response; +} + +export async function deliver(contract: Contract, ship: Ship): Promise { + if (contract.terms.deliver[0].unitsRequired >= contract.terms.deliver[0].unitsFulfilled) { + return await fulfill(contract); + } + const tradeSymbol = contract.terms.deliver[0].tradeSymbol; + let units = 0; + ship.cargo.inventory.forEach(i => {if (i.symbol === tradeSymbol) units = i.units; }); + ship = await libShips.dock(ship); // we need to be docked to deliver + const response = await api.send<{contract: Contract, cargo: Cargo}>({ endpoint: `/my/contracts/${contract.id}/deliver`, method: 'POST', payload: { + shipSymbol: ship.symbol, + tradeSymbol: tradeSymbol, + units: units, + }}); + if ('apiError' in response) { + switch(response.code) { + case 4509: // contract delivery terms have been met + return await fulfill(contract); + default: // yet unhandled error + api.debugLog(response); + throw response; + } + } + dbContracts.setContract(response.contract); + dbShips.setShipCargo(ship.symbol, response.cargo); + if(response.contract.terms.deliver[0].unitsRequired >= response.contract.terms.deliver[0].unitsFulfilled) { + return await fulfill(contract); + } + return response.contract; +} + +export async function fulfill(contract: Contract): Promise { + if (contract.fulfilled) return contract; + const response = await api.send<{agent: Agent, contract: Contract}>({ endpoint: `/my/contracts/${contract.id}/fulfill`, method: 'POST'}); + if ('apiError' in response) { + api.debugLog(response); + throw response; + } + dbAgents.setAgent(response.agent); + dbContracts.setContract(response.contract); + return response.contract; +} diff --git a/nodejs/lib/priority_queue.js b/nodejs/lib/priority_queue.js deleted file mode 100644 index da526b2..0000000 --- a/nodejs/lib/priority_queue.js +++ /dev/null @@ -1,39 +0,0 @@ -export class QElement { - constructor(element, priority) { - this.element = element; - this.priority = priority; - } -} - -export class PriorityQueue { - constructor(elt) { - this.items = []; - if (elt !== undefined) { - this.enqueue(elt, 0); - } - } - - enqueue(element, priority) { - let qElement = new QElement(element, priority); - - for (let i = 0; i < this.items.length; ++i) { - if (this.items[i].priority > qElement.priority) { - this.items.splice(i, 0, qElement); - return; - } - } - this.items.push(qElement); - } - dequeue() { - return this.items.shift(); // we would use pop to get the highest priority, shift() gives us the lowest priority - } - front() { - return this.items[0]; - } - rear() { - return this.items[this.items.length - 1]; - } - isEmpty() { - return this.items.length === 0; - } -} diff --git a/nodejs/lib/priority_queue.ts b/nodejs/lib/priority_queue.ts new file mode 100644 index 0000000..ec9e7d0 --- /dev/null +++ b/nodejs/lib/priority_queue.ts @@ -0,0 +1,36 @@ +class QElement { + element: unknown; + priority: number; + constructor(element: unknown, priority: number) { + this.element = element; + this.priority = priority; + } +} + +export class PriorityQueue { + items: Array; + + constructor(elt?: unknown) { + this.items = []; + if (elt !== undefined) this.enqueue(elt, 0); + } + + enqueue(element: unknown, priority: number): void { + let qElement = new QElement(element, priority); + + for (let i = 0; i < this.items.length; ++i) { + if (this.items[i].priority > qElement.priority) { + this.items.splice(i, 0, qElement); + return; + } + } + this.items.push(qElement); + } + dequeue(): unknown { + // we would use pop to get the highest priority, shift() gives us the lowest priority + return this.items.shift()?.element; + } + isEmpty(): boolean { + return this.items.length === 0; + } +} diff --git a/nodejs/lib/ships.js b/nodejs/lib/ships.js deleted file mode 100644 index 835e62b..0000000 --- a/nodejs/lib/ships.js +++ /dev/null @@ -1,195 +0,0 @@ -import * as api from './api.js'; -import * as dbShips from '../database/ships.js'; -import * as dbSurveys from '../database/surveys.js'; -import * as systems from '../lib/systems.js'; - -export async function extract(ctx) { - const ship = dbShips.getShip(ctx.symbol); - const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ENGINEERED_ASTEROID'}); - // TODO if there are multiple fields, find the closest one? - await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol}); - await orbit(ctx); - // TODO handle surveying? - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/extract`, method: 'POST'}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4000: // ship is on cooldown - await api.sleep(response.error.data.cooldown.remainingSeconds * 1000); - return await extract(ctx); - case 4228: // ship is full - return null; - default: // yet unhandled error - throw response; - } - } else { - dbShips.setShipCargo(ctx.symbol, response.data.cargo); - await api.sleep(response.data.cooldown.remainingSeconds*1000); - } - return response; -} - -export async function dock(ctx) { - const ship = dbShips.getShip(ctx.symbol); - if (ship.nav.status === 'DOCKED') { - return null; - } - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/dock`, method: 'POST'}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4214: // ship is in transit - await api.sleep(response.error.data.secondsToArrival * 1000); - return await dock(ctx); - default: // yet unhandled error - throw response; - } - } - dbShips.setShipNav(ctx.symbol, response.data.nav); - return response; -} - -function hasMount(shipSymbol, mountSymbol) { - const ship = dbShips.getShip(shipSymbol); - return ship.mounts.filter(s => s.symbol === mountSymbol).length > 0; -} - -export async function jump(ctx) { - // TODO - const response = await api.send({endpoint: `/my/ships/${ctx.ship}/jump`, method: 'POST', payload: { systemSymbol: ctx.system }}); - await api.sleep(response.data.cooldown.remainingSeconds*1000); - return response; -} - -export async function navigate(ctx) { - const ship = dbShips.getShip(ctx.symbol); - if (ship.nav.waypointSymbol === ctx.waypoint) { - return; - } - await orbit(ctx); - // TODO if we do not have enough fuel, make a stop to refuel along the way or drift to the destination - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/navigate`, method: 'POST', payload: { waypointSymbol: ctx.waypoint }}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4214: // ship is in transit - await api.sleep(response.error.data.secondsToArrival * 1000); - return await navigate(ctx); - default: // yet unhandled error - throw response; - } - } - dbShips.setShipFuel(ctx.symbol, response.data.fuel); - dbShips.setShipNav(ctx.symbol, response.data.nav); - const delay = new Date(response.data.nav.route.arrival) - new Date(); - await api.sleep(delay); - response.data.nav.status = 'IN_ORBIT'; - dbShips.setShipNav(ctx.symbol, response.data.nav); - await refuel(ctx); - return response; -} - -export async function negotiate(ctx) { - // TODO - return await api.send({endpoint: `/my/ships/${ctx.ship}/negotiate/contract`, method: 'POST'}); -} - -export async function orbit(ctx) { - const ship = dbShips.getShip(ctx.symbol); - if (ship.nav.status === 'IN_ORBIT') { - return null; - } - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/orbit`, method: 'POST'}); - if (response.error !== undefined) { - switch(response.error.code) { - case 4214: // ship is in transit - await api.sleep(response.error.data.secondsToArrival * 1000); - return await orbit(ctx); - default: // yet unhandled error - throw response; - } - } - dbShips.setShipNav(ctx.symbol, response.data.nav); - return response; -} - -export async function purchase(ctx) { - const response = await api.send({endpoint: '/my/ships', method: 'POST', payload: { - shipType: ctx.shipType, - waypointSymbol: ctx.waypoint, - }}); - if (response.error !== undefined) { - throw response; - } - dbShips.setShip(response.data.ship); - return response.data; -} - -export async function refuel(ctx) { - const ship = dbShips.getShip(ctx.symbol); - if (ship.fuel.current >= ship.fuel.capacity * 0.9) { - return null; - } - // TODO check if our current waypoint has a marketplace (and sells fuel)? - await dock(ctx); - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/refuel`, method: 'POST'}); - if (response.error !== undefined) { - throw response; - } - dbShips.setShipFuel(ctx.symbol, response.data.fuel); - // TODO track credits - return response; -} - -export async function sell(ctx) { - // TODO check if our current waypoint has a marketplace? - await dock(ctx); - const ship = dbShips.getShip(ctx.symbol); - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/sell`, method: 'POST', payload: { symbol: ctx.good, units: ctx.units }}); - if (response.error !== undefined) { - throw response; - } - dbShips.setShipCargo(ctx.symbol, response.data.cargo); - // TODO track credits - return response; -} - -export async function ships() { - const response = await api.send({endpoint: `/my/ships`, page: 1}); - if (response.error !== undefined) { - throw response; - } - response.forEach(ship => dbShips.setShip(ship)); - return response; -} - -export async function ship(ctx) { - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}`}); - if (response.error !== undefined) { - throw response; - } - dbShips.setShip(response.data); - return response; -} - -export async function survey(ctx) { - if (!hasMount(ctx.symbol, 'MOUNT_SURVEYOR_I')) { // we check if a surveyor is mounted on the ship - return null; - } - const ship = dbShips.getShip(ctx.symbol); - const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ASTEROID_FIELD'}); - // TODO if there are multiple fields, find the closest one? - await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol}); - await orbit(ctx); - const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/survey`, method: 'POST'}); - api.debugLog(response); - if (response.error !== undefined) { - switch(response.error.code) { - case 4000: // ship is on cooldown - await api.sleep(response.error.data.cooldown.remainingSeconds * 1000); - return await survey(ctx); - default: // yet unhandled error - throw response; - } - } - dbSurveys.set(response.data.surveys[0]); - await api.sleep(response.data.cooldown.remainingSeconds*1000); - return response; -} diff --git a/nodejs/lib/ships.ts b/nodejs/lib/ships.ts new file mode 100644 index 0000000..2e04dd4 --- /dev/null +++ b/nodejs/lib/ships.ts @@ -0,0 +1,204 @@ +import { Response } from '../model/api.ts'; +import { Agent } from '../model/agent.ts'; +import { Cargo } from '../model/cargo.ts'; +import { Cooldown, Fuel, Nav, Ship } from '../model/ship.ts'; +import * as api from './api.js'; +import * as dbAgents from '../database/agents.ts'; +import * as dbShips from '../database/ships.js'; +import * as dbSurveys from '../database/surveys.js'; +import * as systems from '../lib/systems.js'; + +export async function dock(ship: Ship): Promise { + if (ship.nav.status === 'DOCKED') return ship; + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/dock`, method: 'POST'}) as Response<{nav: Nav}>; + if (response.error !== undefined) { + switch(response.error.code) { + case 4214: // ship is in transit + await api.sleep(response.error.data.secondsToArrival * 1000); + return await dock(ship); + default: // yet unhandled error + api.debugLog(response); + throw response; + } + } + dbShips.setShipNav(ship.symbol, response.data.nav); + ship.nav = response.data.nav; + return ship; +} + +export async function extract(ship: Ship): Promise { + // TODO move to a suitable asteroid? + // const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ENGINEERED_ASTEROID'}); + // TODO if there are multiple fields, find the closest one? + //await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol}); + ship = await orbit(ship); + // TODO handle surveying? + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/extract`, method: 'POST'}) as Response<{cooldown: Cooldown, cargo: Cargo}>; // TODO extraction and events api response fields cf https://spacetraders.stoplight.io/docs/spacetraders/b3931d097608d-extract-resources + if (response.error !== undefined) { + switch(response.error.code) { + case 4000: // ship is on cooldown + await api.sleep(response.error.data.cooldown.remainingSeconds * 1000); + return await extract(ship); + case 4228: // ship is full + return ship; + default: // yet unhandled error + api.debugLog(response); + throw response; + } + } else { + dbShips.setShipCargo(ship.symbol, response.data.cargo); + ship.cargo = response.data.cargo; + await api.sleep(response.data.cooldown.remainingSeconds*1000); + } + return ship; +} + +//function hasMount(shipSymbol, mountSymbol) { +// const ship = dbShips.getShip(shipSymbol); +// return ship.mounts.filter(s => s.symbol === mountSymbol).length > 0; +//} + +//export async function jump(ship: Ship): Ship { +// // TODO +// const response = await api.send({endpoint: `/my/ships/${ctx.ship}/jump`, method: 'POST', payload: { systemSymbol: ctx.system }}); +// await api.sleep(response.data.cooldown.remainingSeconds*1000); +// return response; +//} + +export async function navigate(ship: Ship, waypoint: string): Promise { + if (ship.nav.waypointSymbol === waypoint) return ship; + ship = await orbit(ship); + // TODO if we do not have enough fuel, make a stop to refuel along the way or drift to the destination + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/navigate`, method: 'POST', payload: { waypointSymbol: waypoint }}) as Response<{fuel: Fuel, nav: Nav}>; // TODO events field + if (response.error !== undefined) { + switch(response.error.code) { + case 4214: // ship is in transit + await api.sleep(response.error.data.secondsToArrival * 1000); + return await navigate(ship, waypoint); + default: // yet unhandled error + api.debugLog(response); + throw response; + } + } + dbShips.setShipFuel(ship.symbol, response.data.fuel); + dbShips.setShipNav(ship.symbol, response.data.nav); + ship.fuel = response.data.fuel; + ship.nav = response.data.nav + const delay = new Date(response.data.nav.route.arrival).getTime() - new Date().getTime() ; + await api.sleep(delay); + response.data.nav.status = 'IN_ORBIT'; // we arrive in orbit + dbShips.setShipNav(ship.symbol, response.data.nav); + ship.nav = response.data.nav + ship = await refuel(ship); + return ship; +} + +//export async function negotiate(ctx) { +// // TODO +// return await api.send({endpoint: `/my/ships/${ctx.ship}/negotiate/contract`, method: 'POST'}); +//} + +export async function orbit(ship: Ship): Promise { + if (ship.nav.status === 'IN_ORBIT') return ship; + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/orbit`, method: 'POST'}) as Response<{nav: Nav}>; + if (response.error !== undefined) { + switch(response.error.code) { + case 4214: // ship is in transit + await api.sleep(response.error.data.secondsToArrival * 1000); + return await orbit(ship); + default: // yet unhandled error + throw response; + } + } + dbShips.setShipNav(ship.symbol, response.data.nav); + ship.nav = response.data.nav; + return ship; +} + +//export async function purchase(ctx) { +// const response = await api.send({endpoint: '/my/ships', method: 'POST', payload: { +// shipType: ctx.shipType, +// waypointSymbol: ctx.waypoint, +// }}); +// if (response.error !== undefined) { +// throw response; +// } +// dbShips.setShip(response.data.ship); +// return response.data; +//} + +export async function refuel(ship: Ship): Promise { + if (ship.fuel.current >= ship.fuel.capacity * 0.9) return ship; + // TODO check if our current waypoint has a marketplace (and sells fuel)? + ship = await dock(ship); + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/refuel`, method: 'POST'}) as Response<{agent: Agent, fuel: Fuel}>; // TODO transaction field + if (response.error !== undefined) { + api.debugLog(response); + throw response; + } + dbShips.setShipFuel(ship.symbol, response.data.fuel); + dbAgents.setAgent(response.data.agent); + ship.fuel = response.data.fuel; + return ship; +} + +export async function sell(ship: Ship, tradeSymbol: string): Promise { + // TODO check if our current waypoint has a marketplace? + ship = await dock(ship); + let units = 0; + ship.cargo.inventory.forEach(i => {if (i.symbol === tradeSymbol) units = i.units; }); + const response = await api.send({endpoint: `/my/ships/${ship.symbol}/sell`, method: 'POST', payload: { symbol: tradeSymbol, units: units }}) as Response<{agent: Agent, cargo: Cargo}>; // TODO transaction field + if (response.error !== undefined) { + api.debugLog(response); + throw response; + } + dbShips.setShipCargo(ship.symbol, response.data.cargo); + dbAgents.setAgent(response.data.agent); + ship.cargo = response.data.cargo; + return ship; +} + +export async function ships(): Promise> { + const response = await api.send({endpoint: `/my/ships`, page: 1}) as Response>; + if (response.error !== undefined) { + api.debugLog(response); + throw response; + } + response.data.forEach(ship => dbShips.setShip(ship)); + return response.data; +} + +export async function ship(ship: Ship): Promise { + const response = await api.send({endpoint: `/my/ships/${ship.symbol}`}) as Response; + if (response.error !== undefined) { + api.debugLog(response); + throw response; + } + dbShips.setShip(response.data); + return response.data; +} + +//export async function survey(ctx) { +// if (!hasMount(ctx.symbol, 'MOUNT_SURVEYOR_I')) { // we check if a surveyor is mounted on the ship +// return null; +// } +// const ship = dbShips.getShip(ctx.symbol); +// const asteroidFields = await systems.type({symbol: ship.nav.systemSymbol, type: 'ASTEROID_FIELD'}); +// // TODO if there are multiple fields, find the closest one? +// await navigate({symbol: ctx.symbol, waypoint: asteroidFields[0].symbol}); +// await orbit(ctx); +// const response = await api.send({endpoint: `/my/ships/${ctx.symbol}/survey`, method: 'POST'}); +// api.debugLog(response); +// if (response.error !== undefined) { +// switch(response.error.code) { +// case 4000: // ship is on cooldown +// await api.sleep(response.error.data.cooldown.remainingSeconds * 1000); +// return await survey(ctx); +// default: // yet unhandled error +// throw response; +// } +// } +// dbSurveys.set(response.data.surveys[0]); +// await api.sleep(response.data.cooldown.remainingSeconds*1000); +// return response; +//} diff --git a/nodejs/lib/systems.js b/nodejs/lib/systems.js deleted file mode 100644 index 6993431..0000000 --- a/nodejs/lib/systems.js +++ /dev/null @@ -1,86 +0,0 @@ -import * as api from './api.js'; -import * as dbMarkets from '../database/markets.js'; -import * as dbShips from '../database/ships.js'; -import * as dbSystems from '../database/systems.js'; -import * as utils from './utils.js'; - -// Retrieves a marketplace's market data for waypointSymbol -export async function market(waypointSymbol) { - const data = dbMarkets.getMarketAtWaypoint(waypointSymbol); - if (data === null) { - if (dbShips.getShipsAt(waypointSymbol) === null) { - return null; - } - const systemSymbol = utils.systemFromWaypoint(waypointSymbol); - let d = await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${waypointSymbol}/market`}); - delete d.data.transactions; - dbMarkets.setMarket(d.data); - return d; - } - return data; -} - -// Retrieves a shipyard's information for ctx.symbol -export async function shipyard(ctx) { - const systemSymbol = utils.systemFromWaypoint(ctx.symbol); - return await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${ctx.symbol}/shipyard`}); -} - -// Retrieves the system's information for ctx.symbol and caches it in the database -export async function system(ctx) { - let s = dbSystems.getSystem(ctx.symbol); - if (s === null) { - const response = await api.send({endpoint: `/systems/${ctx.symbol}`}); - if (response.error !== undefined) { - switch(response.error.code) { - case 404: - throw `Error retrieving info for system ${ctx.symbol}: ${response.error.message}`; - default: // yet unhandled error - throw response; - } - } - s = response.data; - dbSystems.setSystem(s); - } - return s; -} - -// Retrieves a list of waypoints that have a specific ctx.trait like a SHIPYARD or a MARKETPLACE in the system ctx.symbol -export async function trait(ctx) { - const w = await waypoints(ctx); - return w.filter(s => s.traits.some(t => t.symbol === ctx.trait)); -} - -// Retrieves a list of waypoints that have a specific ctx.type like ASTEROID_FIELD in the system ctx.symbol -export async function type(ctx, response) { - const w = await waypoints(ctx); - return w.filter(s => s.type === ctx.type); -} - -// Retrieves the system's information for ctx.symbol and caches it in the database -export async function waypoints(ctx) { - await system(ctx); - let updated = dbSystems.getSystemUpdated(ctx.symbol); - // TODO handle uncharted systems - if (updated === null) { - let waypoints = []; - for (let page=1; true; ++page) { - const response = await api.send({endpoint: `/systems/${ctx.symbol}/waypoints?limit=20&page=${page}`, priority: 98}); - if (response.error !== undefined) { - switch(response.error.code) { - case 404: - throw `Error retrieving waypoints for system ${ctx.symbol}: ${response.error.message}`; - default: // yet unhandled error - throw response; - } - } - waypoints = waypoints.concat(response.data); - if (response.meta.total <= response.meta.limit * page) { - break; - } - } - dbSystems.setSystemWaypoints(ctx.symbol, waypoints); - return waypoints; - } - return dbSystems.getSystem(ctx.symbol).waypoints; -} diff --git a/nodejs/lib/systems.ts b/nodejs/lib/systems.ts new file mode 100644 index 0000000..94ebab7 --- /dev/null +++ b/nodejs/lib/systems.ts @@ -0,0 +1,86 @@ +import * as api from './api.js'; +import * as dbMarkets from '../database/markets.js'; +import * as dbShips from '../database/ships.js'; +import * as dbSystems from '../database/systems.js'; +import * as utils from './utils.js'; + +// Retrieves a marketplace's market data for waypointSymbol +export async function market(waypointSymbol: string) { + const data = dbMarkets.getMarketAtWaypoint(waypointSymbol); + if (data === null) { + if (dbShips.getShipsAt(waypointSymbol) === null) { + return null; + } + const systemSymbol = utils.systemFromWaypoint(waypointSymbol); + let d = await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${waypointSymbol}/market`}); + delete d.data.transactions; + dbMarkets.setMarket(d.data); + return d; + } + return data; +} + +// Retrieves a shipyard's information for ctx.symbol +export async function shipyard(ctx) { + const systemSymbol = utils.systemFromWaypoint(ctx.symbol); + return await api.send({endpoint: `/systems/${systemSymbol}/waypoints/${ctx.symbol}/shipyard`}); +} + +// Retrieves the system's information for ctx.symbol and caches it in the database +export async function system(ctx) { + let s = dbSystems.getSystem(ctx.symbol); + if (s === null) { + const response = await api.send({endpoint: `/systems/${ctx.symbol}`}); + if (response.error !== undefined) { + switch(response.error.code) { + case 404: + throw `Error retrieving info for system ${ctx.symbol}: ${response.error.message}`; + default: // yet unhandled error + throw response; + } + } + s = response.data; + dbSystems.setSystem(s); + } + return s; +} + +// Retrieves a list of waypoints that have a specific ctx.trait like a SHIPYARD or a MARKETPLACE in the system ctx.symbol +export async function trait(ctx) { + const w = await waypoints(ctx); + return w.filter(s => s.traits.some(t => t.symbol === ctx.trait)); +} + +// Retrieves a list of waypoints that have a specific ctx.type like ASTEROID_FIELD in the system ctx.symbol +export async function type(ctx, response) { + const w = await waypoints(ctx); + return w.filter(s => s.type === ctx.type); +} + +// Retrieves the system's information for ctx.symbol and caches it in the database +export async function waypoints(ctx) { + await system(ctx); + let updated = dbSystems.getSystemUpdated(ctx.symbol); + // TODO handle uncharted systems + if (updated === null) { + let waypoints = []; + for (let page=1; true; ++page) { + const response = await api.send({endpoint: `/systems/${ctx.symbol}/waypoints?limit=20&page=${page}`, priority: 98}); + if (response.error !== undefined) { + switch(response.error.code) { + case 404: + throw `Error retrieving waypoints for system ${ctx.symbol}: ${response.error.message}`; + default: // yet unhandled error + throw response; + } + } + waypoints = waypoints.concat(response.data); + if (response.meta.total <= response.meta.limit * page) { + break; + } + } + dbSystems.setSystemWaypoints(ctx.symbol, waypoints); + return waypoints; + } + return dbSystems.getSystem(ctx.symbol).waypoints; +} diff --git a/nodejs/lib/utils.js b/nodejs/lib/utils.js deleted file mode 100644 index a2c8128..0000000 --- a/nodejs/lib/utils.js +++ /dev/null @@ -1,18 +0,0 @@ -// cargo is a ship.cargo object, want is an optional symbol -export function categorizeCargo(cargo, want) { - const wanted = cargo.inventory.filter(i => i.symbol === want || i.symbol === 'ANTIMATTER'); - const goods = cargo.inventory.filter(i => i.symbol !== want && i.symbol !== 'ANTIMATTER'); - const wobj = wanted.reduce(function(acc, e) { - acc[e.symbol] = e.units; - return acc; - }, {}); - const gobj = goods.reduce(function(acc, e) { - acc[e.symbol] = e.units; - return acc; - }, {}); - return {wanted: wobj, goods: gobj}; -} - -export function systemFromWaypoint(waypoint) { - return waypoint.split('-').slice(0,2).join('-'); -} diff --git a/nodejs/lib/utils.ts b/nodejs/lib/utils.ts new file mode 100644 index 0000000..c5093a6 --- /dev/null +++ b/nodejs/lib/utils.ts @@ -0,0 +1,25 @@ +import { Cargo, CargoManifest } from '../model/cargo.ts'; + +export type CategorizedCargo = { + wanted: CargoManifest; + goods: CargoManifest; +}; + +// cargo is a ship.cargo object, want is an optional symbol +export function categorizeCargo(cargo: Cargo, want?: string): CategorizedCargo { + const wanted = cargo.inventory.filter(i => i.symbol === want || i.symbol === 'ANTIMATTER'); + const goods = cargo.inventory.filter(i => i.symbol !== want && i.symbol !== 'ANTIMATTER'); + const wobj = wanted.reduce(function(acc: CargoManifest, e) { + acc[e.symbol] = e.units; + return acc; + }, {}); + const gobj = goods.reduce(function(acc: CargoManifest, e) { + acc[e.symbol] = e.units; + return acc; + }, {}); + return {wanted: wobj, goods: gobj}; +} + +export function systemFromWaypoint(waypoint: string): string { + return waypoint.split('-').slice(0,2).join('-'); +} -- cgit v1.2.3