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

migrate token pooling to postgres #8922

Merged
merged 4 commits into from
Feb 23, 2023
Merged
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
8 changes: 8 additions & 0 deletions .github/actions/integration-tests/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,19 @@ inputs:
runs:
using: 'composite'
steps:
- name: Migrate DB
if: always()
run: npm run migrate up
env:
POSTGRES_URL: postgresql://postgres:postgres@localhost:5432/ci_test
shell: bash

- name: Integration Tests
if: always()
run: npm run test:integration -- --reporter json --reporter-option 'output=reports/integration-tests.json'
env:
GH_TOKEN: '${{ inputs.github-token }}'
POSTGRES_URL: postgresql://postgres:postgres@localhost:5432/ci_test
shell: bash

- name: Write Markdown Summary
Expand Down
13 changes: 13 additions & 0 deletions .github/workflows/test-integration-17.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ jobs:
--health-retries 5
ports:
- 6379:6379
postgres:
image: postgres
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: ci_test
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432

steps:
- name: Checkout
Expand Down
13 changes: 13 additions & 0 deletions .github/workflows/test-integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,19 @@ jobs:
--health-retries 5
ports:
- 6379:6379
postgres:
image: postgres
env:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: ci_test
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432

steps:
- name: Checkout
Expand Down
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -117,3 +117,6 @@ service-definitions.yml

# Flamebearer
flamegraph.html

# config file for node-pg-migrate
migrations-config.json
1 change: 1 addition & 0 deletions config/custom-environment-variables.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ private:
obs_user: 'OBS_USER'
obs_pass: 'OBS_PASS'
redis_url: 'REDIS_URL'
postgres_url: 'POSTGRES_URL'
sentry_dsn: 'SENTRY_DSN'
sl_insight_userUuid: 'SL_INSIGHT_USER_UUID'
sl_insight_apiToken: 'SL_INSIGHT_API_TOKEN'
Expand Down
1 change: 1 addition & 0 deletions core/server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,7 @@ const privateConfigSchema = Joi.object({
obs_user: Joi.string(),
obs_pass: Joi.string(),
redis_url: Joi.string().uri({ scheme: ['redis', 'rediss'] }),
postgres_url: Joi.string().uri({ scheme: 'postgresql' }),
sentry_dsn: Joi.string(),
sl_insight_userUuid: Joi.string(),
sl_insight_apiToken: Joi.string(),
Expand Down
1 change: 0 additions & 1 deletion core/token-pooling/redis-token-persistence.integration.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,6 @@ describe('Redis token persistence', function () {
const toRemove = expected.pop()

await persistence.initialize()

await persistence.noteTokenRemoved(toRemove)

const savedTokens = await redis.smembers(key)
Expand Down
103 changes: 103 additions & 0 deletions core/token-pooling/sql-token-persistence.integration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import pg from 'pg'
import { expect } from 'chai'
import configModule from 'config'
import SqlTokenPersistence from './sql-token-persistence.js'

const config = configModule.util.toObject()
const postgresUrl = config?.private?.postgres_url
const tableName = 'token_persistence_integration_test'

describe('SQL token persistence', function () {
let pool
let persistence

before('Mock db connection and load app', async function () {
// Create a new pool with a connection limit of 1
pool = new pg.Pool({
connectionString: postgresUrl,

// Reuse the connection to make sure we always hit the same pg_temp schema
max: 1,

// Disable auto-disconnection of idle clients to make sure we always hit the same pg_temp schema
idleTimeoutMillis: 0,
})
persistence = new SqlTokenPersistence({
url: postgresUrl,
table: tableName,
})
})
after(async function () {
if (persistence) {
await persistence.stop()
persistence = undefined
}
})

beforeEach('Create temporary table', async function () {
await pool.query(
`CREATE TEMPORARY TABLE ${tableName} (LIKE github_user_tokens INCLUDING ALL);`
)
})
afterEach('Drop temporary table', async function () {
await pool.query(`DROP TABLE IF EXISTS pg_temp.${tableName};`)
})
Comment on lines +37 to +44
Copy link
Member Author

Choose a reason for hiding this comment

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

This copies our table to a temp schema for the purposes of running the tests then clears it up again after. This means we can run the tests against a local DB with real data in it and not break our local data. We don't need a separate test DB. It also means the tests will keep step with schema changes from the migrations. We do need to migrate up before running the tests though.

Copy link
Member

Choose a reason for hiding this comment

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

This means we can run the tests against a local DB with real data in it and not break our local data. We don't need a separate test DB. It also means the tests will keep step with schema changes from the migrations. We do need to migrate up before running the tests though

No objections to this in the local/inner dev loop (nor CI) context, and agree the benefits outweigh the tradeoffs. Would be nervous abut this in the context of the real DB though (whether connected to deliberately or accidentally)

Copy link
Member Author

Choose a reason for hiding this comment

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

In principle it should be safe but I agree - I wouldn't want to run the tests while connected to the prod DB. Tbh that would be fairly unusual thing to do for any application. I think the fact that the dev dependencies (e.g: mocha, etc) aren't installed in the prod container is enough of a guard rail to stop this from happening.

Personally I'd tend to avoid connecting my dev environment up to a prod database for any application.


context('when the key does not exist', function () {
it('does nothing', async function () {
const tokens = await persistence.initialize(pool)
expect(tokens).to.deep.equal([])
})
})

context('when the key exists', function () {
const initialTokens = ['a', 'b', 'c'].map(char => char.repeat(40))

beforeEach(async function () {
initialTokens.forEach(async token => {
await pool.query(
`INSERT INTO pg_temp.${tableName} (token) VALUES ($1::text);`,
[token]
)
})
})
chris48s marked this conversation as resolved.
Show resolved Hide resolved

it('loads the contents', async function () {
const tokens = await persistence.initialize(pool)
expect(tokens.sort()).to.deep.equal(initialTokens)
})

context('when tokens are added', function () {
it('saves the change', async function () {
const newToken = 'e'.repeat(40)
const expected = initialTokens.slice()
expected.push(newToken)

await persistence.initialize(pool)
await persistence.noteTokenAdded(newToken)

const result = await pool.query(
`SELECT token FROM pg_temp.${tableName};`
)
const savedTokens = result.rows.map(row => row.token)
expect(savedTokens.sort()).to.deep.equal(expected)
})
})

context('when tokens are removed', function () {
it('saves the change', async function () {
const expected = Array.from(initialTokens)
const toRemove = expected.pop()

await persistence.initialize(pool)
await persistence.noteTokenRemoved(toRemove)

const result = await pool.query(
`SELECT token FROM pg_temp.${tableName};`
)
const savedTokens = result.rows.map(row => row.token)
expect(savedTokens.sort()).to.deep.equal(expected)
chris48s marked this conversation as resolved.
Show resolved Hide resolved
})
})
})
})
55 changes: 55 additions & 0 deletions core/token-pooling/sql-token-persistence.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import pg from 'pg'
import log from '../server/log.js'

export default class SqlTokenPersistence {
constructor({ url, table }) {
this.url = url
this.table = table
this.noteTokenAdded = this.noteTokenAdded.bind(this)
this.noteTokenRemoved = this.noteTokenRemoved.bind(this)
}

async initialize(pool) {
if (pool) {
this.pool = pool
} else {
this.pool = new pg.Pool({ connectionString: this.url })
}
const result = await this.pool.query(`SELECT token FROM ${this.table};`)
return result.rows.map(row => row.token)
}

async stop() {
await this.pool.end()
}

async onTokenAdded(token) {
return await this.pool.query(
`INSERT INTO ${this.table} (token) VALUES ($1::text) ON CONFLICT (token) DO NOTHING;`,
chris48s marked this conversation as resolved.
Show resolved Hide resolved
[token]
)
}

async onTokenRemoved(token) {
return await this.pool.query(
`DELETE FROM ${this.table} WHERE token=$1::text;`,
[token]
)
}

async noteTokenAdded(token) {
try {
await this.onTokenAdded(token)
} catch (e) {
log.error(e)
}
}

async noteTokenRemoved(token) {
try {
await this.onTokenRemoved(token)
} catch (e) {
log.error(e)
}
}
}
14 changes: 14 additions & 0 deletions migrations/1676731511125_initialize.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/* eslint-disable camelcase */
chris48s marked this conversation as resolved.
Show resolved Hide resolved

exports.shorthands = undefined
Copy link
Member

Choose a reason for hiding this comment

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

What's this?

Copy link
Member Author

Choose a reason for hiding this comment

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


exports.up = pgm => {
pgm.createTable('github_user_tokens', {
id: 'id',
token: { type: 'varchar(1000)', notNull: true, unique: true },
})
}

exports.down = pgm => {
pgm.dropTable('github_user_tokens')
}
Loading