Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

William/v2 prototype #40

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

This server sends push notifications to Edge client apps. It contains an HTTP server that clients can use to register for notifications, and a background process that checks for price changes and actually sends the messages.

The docs folder has can find [an example of how to use the v2 API](./docs/demo.ts).

## Setup

This server requires a working copies of Node.js, Yarn, PM2, and CouchDB. We also recommend using Caddy to terminate SSL connections.
Expand Down
112 changes: 112 additions & 0 deletions docs/demo.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { asJSON, asMaybe, asObject, asString, uncleaner } from 'cleaners'
import fetch from 'node-fetch'
import { base64 } from 'rfc4648'

import {
asDeviceUpdatePayload,
asLoginUpdatePayload,
asPushRequestBody
} from '../src/types/pushApiTypes'

// We are going to use uncleaners to type-check our payloads:
const wasPushRequestBody = uncleaner(asPushRequestBody)
const wasDeviceUpdatePayload = uncleaner(asDeviceUpdatePayload)
const wasLoginUpdatePayload = uncleaner(asLoginUpdatePayload)

/**
* Failed requests usually return this as their body.
*/
const asErrorBody = asJSON(
asObject({
error: asString
})
)

const apiKey = 'demo-api-key'
const deviceId = 'example-device'
const loginId = base64.parse('EE+tBb5wM63qwCDVidzwUQThH9ekCSfpUuTQYujSmY8=')
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this loginId a test loginId?


/**
* All push server HTTP methods use "POST" with JSON.
*/
async function postJson(uri: string, body: unknown): Promise<unknown> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I wish I had noticed this function early. I like it and would prefer to use it in the GUI (if not now, then later).

console.log(JSON.stringify(body, null, 1))
const response = await fetch(uri, {
body: JSON.stringify(body),
headers: {
accept: 'application/json',
'content-type': 'application/json'
},
method: 'POST'
})
if (!response.ok) {
const error = asMaybe(asErrorBody)(await response.text())
let message = `POST ${uri} returned ${response.status}`
if (error != null) message += `: ${error.error}`
throw new Error(message)
}
return await response.json()
}

async function main(): Promise<void> {
// Create a device:
await postJson(
'http://127.0.0.1:8001/v2/device/update/',
wasPushRequestBody({
apiKey,
deviceId,
data: wasDeviceUpdatePayload({ loginIds: [loginId] })
})
)
Comment on lines +53 to +60
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This would be the isomorphic dream:

import pushServer from 'https://push.edge.app/api'

pushServer.device.update({ apiKey, deviceId, data: { loginIds: [loginId] } })

This magic would be enabled with URL imports in our client-side environments (something Deno or Bun enables) and using a special HTTP server framework (ala serverlet) which could syndicate a public API derived from the defined routes at the /api route.

TL;DR: Another thing to add to the side-project/experiment list.

console.log(`Updated device "${deviceId}"`)

// Grab the device status:
console.log(
await postJson(
'http://127.0.0.1:8001/v2/device/',
wasPushRequestBody({ apiKey, deviceId })
)
)

// Subscribe the user to a price change:
await postJson(
'http://127.0.0.1:8001/v2/login/update/',
wasPushRequestBody({
apiKey,
deviceId,
loginId,
data: wasLoginUpdatePayload({
createEvents: [
{
eventId: 'demo-event',
pushMessage: {
title: 'Example title',
body: 'Example body',
data: { what: 'happened' }
},
recurring: false,
trigger: {
type: 'price-level',
currencyPair: 'BTC-USD',
aboveRate: 50000
}
}
]
})
})
)
console.log(`Updated login "${base64.stringify(loginId)}"`)

// Grab the login status:
console.log(
await postJson(
'http://127.0.0.1:8001/v2/login/',
wasPushRequestBody({ apiKey, deviceId, loginId })
)
)
}

main().catch(error => {
console.error(String(error))
process.exitCode = 1
})
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"scripts": {
"build": "sucrase -q -t typescript,imports -d ./lib ./src",
"clean": "rimraf lib",
"demo": "node -r sucrase/register docs/demo.ts",
"fix": "yarn-deduplicate && eslint . --fix",
"lint": "eslint .",
"precommit": "lint-staged && npm-run-all types prepare",
Expand All @@ -34,6 +35,7 @@
"firebase-admin": "^8.12.1",
"nano": "^9.0.5",
"node-fetch": "^2.6.7",
"rfc4648": "^1.5.2",
"serverlet": "^0.1.1"
},
"devDependencies": {
Expand Down
173 changes: 173 additions & 0 deletions src/db/couchDevices.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
import {
asArray,
asDate,
asObject,
asOptional,
asString,
uncleaner
} from 'cleaners'
import {
asCouchDoc,
asMaybeConflictError,
asMaybeNotFoundError,
DatabaseSetup,
makeJsDesign
} from 'edge-server-tools'
import { ServerScope } from 'nano'
import { base64 } from 'rfc4648'

import { asBase64 } from '../types/pushCleaners'
import { Device } from '../types/pushTypes'

/**
* A device returned from the database.
* Mutate the `device` object, then call `save` to commit the changes.
*/
export interface DeviceRow {
device: Device
save: () => Promise<void>
}

/**
* An API key, as stored in Couch.
*/
export const asCouchDevice = asCouchDoc<Omit<Device, 'deviceId'>>(
asObject({
created: asDate,

// Status:
apiKey: asOptional(asString),
deviceToken: asOptional(asString),
loginIds: asArray(asBase64),
visited: asDate
})
)
const wasCouchDevice = uncleaner(asCouchDevice)
type CouchDevice = ReturnType<typeof asCouchDevice>

/**
* Looks up devices that contain a particular login.
*/
const loginIdDesign = makeJsDesign('loginId', ({ emit }) => ({
map: function (doc) {
for (let i = 0; i < doc.loginIds.length; ++i) {
emit(doc.loginIds[i], null)
}
}
}))

export const couchDevicesSetup: DatabaseSetup = {
name: 'push-devices',
documents: {
'_design/loginId': loginIdDesign
}
}

/**
* Looks up a device by its id.
* If the device does not exist in the database, creates a fresh row.
*/
export async function getDeviceById(
connection: ServerScope,
deviceId: string,
date: Date
): Promise<DeviceRow> {
const db = connection.use(couchDevicesSetup.name)
const raw = await db.get(deviceId).catch(error => {
if (asMaybeNotFoundError(error) != null) return
throw error
})

if (raw == null) {
return makeDeviceRow(connection, {
created: date,
deviceId,
apiKey: undefined,
deviceToken: undefined,
loginIds: [],
visited: date
})
}
const clean = asCouchDevice(raw)
return makeDeviceRow(
connection,
{ ...clean.doc, deviceId: clean.id },
clean.rev
)
}

/**
* Finds all the devices that have logged into this account.
*/
export async function getDevicesByLoginId(
connection: ServerScope,
loginId: Uint8Array
): Promise<DeviceRow[]> {
const db = connection.use(couchDevicesSetup.name)
const response = await db.view('loginId', 'loginId', {
include_docs: true,
key: base64.stringify(loginId)
})
return response.rows.map(row => {
const clean = asCouchDevice(row.doc)
return makeDeviceRow(
connection,
{ ...clean.doc, deviceId: clean.id },
clean.rev
)
})
}

function makeDeviceRow(
connection: ServerScope,
device: Device,
rev?: string
): DeviceRow {
const db = connection.db.use(couchDevicesSetup.name)
let base = { ...device }

return {
device,

async save(): Promise<void> {
while (true) {
// Write to the database:
const doc: CouchDevice = {
doc: device,
id: device.deviceId,
rev
}
const response = await db.insert(wasCouchDevice(doc)).catch(error => {
if (asMaybeConflictError(error) == null) throw error
})

// If that worked, the merged document is now the latest:
if (response?.ok === true) {
base = { ...device }
rev = doc.rev
return
}

// Something went wrong, so grab the latest remote document:
const raw = await db.get(device.deviceId)
const clean = asCouchDevice(raw)
rev = clean.rev
const remote = clean.doc

// If we don't have local edits, take the remote field:
if (device.apiKey === base.apiKey) {
device.apiKey = remote.apiKey
}
if (device.deviceToken === base.deviceToken) {
device.deviceToken = remote.deviceToken
}
if (device.loginIds === base.loginIds) {
device.loginIds = remote.loginIds
}
if (remote.visited > device.visited) {
device.visited = remote.visited
}
}
}
}
}
Loading