Issues with redis-rails and connection_pool - ruby-on-rails

How I can initialize my redis_store to have connection pooling. I want to add pooling attributes { pool_size: 10, pool_timeout: 10 } I have added connection_pool gem
Example::Application.config.session_store :redis_store,
servers: { host: 'localhost',
port: 6379,
db: 0,
namespace: 'session'
},
expires_in: 25.hours,
It gives error on server boot. If I add something like below;
Example::Application.config.session_store :redis_store,
servers: { host: 'localhost',
port: 6379,
db: 0,
namespace: 'session'
},
expires_in: 25.hours,
{ pool_size: 10, pool_timeout: 10 }

After I'd executed your code, I've run into a simple SyntaxError. Might be your problem, since the correct specifying of the options should be:
Example::Application.config.session_store :redis_store,
servers: { host: 'localhost',
port: 6379,
db: 0,
namespace: 'session'
},
expires_in: 25.hours,
pool_size: 10,
pool_timeout: 10

Related

How to add environment variables in config.json?

I am working on a database migration project and it requires me to use sequelize. I initialized sequelize's CLI (using npx sequelize-cli init) that added the config.json file:
config, contains config file, which tells CLI how to connect with database
The config.json file has this object:
"production": {
"username": "root",
"password": null,
"database": "database_production",
"host": "127.0.0.1",
"dialect": "mysql"
}
But I don't want to save my password in a config.json file. I want to use an environmental variable instead. What can I do?
Rename the config.json to config.js, install dotenv and use the below code
require('dotenv').config();
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
},
test: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
},
production: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
}
};
First you have to create a .sequelizerc file in root. Then add the following code there.
var path = require('path')
module.exports = {
'config': path.resolve('config', 'config.js'),
}
Note: Change the path as per your project.
Then you can rename the config.json file to config.js and add the below code there. (As in Tunde's answer.)
require('dotenv').config();
module.exports = {
development: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
},
test: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
},
production: {
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: process.env.DB_DRIVER
}
};

Vue CLI HMR not working after upgrading to v5

I'm developing a Django+Vue app using VSCode devcontainers (Docker).
I have recently migrated from Vue CLI v4 to Vue CLI v5 following the migration guide.
After the migration, the HMR of the dev-server stopped working.
This was my vue.config.js before the migration:
const BundleTracker = require("webpack-bundle-tracker");
module.exports = {
publicPath: process.env.NODE_ENV === "development" ? "http://localhost:8080/" : "/static/",
devServer: {
host: "0.0.0.0",
port: 8080,
public: "0.0.0.0:8080",
https: false,
headers: { "Access-Control-Allow-Origin": ["*"] },
hotOnly: true,
watchOptions: {
ignored: "./node_modules/",
aggregateTimeout: 300,
poll: 1000,
},
},
transpileDependencies: ["vuetify"],
css: {
sourceMap: true,
},
chainWebpack: (config) => {
config.plugin("BundleTracker").use(BundleTracker, [
{
filename: `./config/webpack-stats-${process.env.NODE_ENV}.json`,
},
]);
config.resolve.alias.set("__STATIC__", "static");
},
};
And after:
const { defineConfig } = require("#vue/cli-service");
const BundleTracker = require("webpack-bundle-tracker");
module.exports = defineConfig({
publicPath: process.env.NODE_ENV === "development" ? "http://localhost:8080/" : "/static/",
devServer: {
host: "0.0.0.0",
port: 8080,
client: {
webSocketURL: "auto://0.0.0.0:8080/ws",
},
https: false,
headers: { "Access-Control-Allow-Origin": ["*"] },
hot: "only",
static: {
watch: {
ignored: "./node_modules/",
aggregateTimeout: 300,
poll: 1000,
},
},
},
transpileDependencies: ["vuetify"],
css: {
sourceMap: true,
},
chainWebpack: (config) => {
config.plugin("BundleTracker").use(BundleTracker, [
{
filename: `./config/webpack-stats-${process.env.NODE_ENV}.json`,
},
]);
config.resolve.alias.set("__STATIC__", "static");
},
});
After the migration, a new warning shows everytime I run npm run serve (but devServer.public has been removed in v5!):
App running at:
- Local: http://localhost:8080/
It seems you are running Vue CLI inside a container.
Since you are using a non-root publicPath, the hot-reload socket
will not be able to infer the correct URL to connect. You should
explicitly specify the URL via devServer.public.
Access the dev server via http://localhost:<your container's external mapped port>http://localhost:8080/
Note that the development build is not optimized.
To create a production build, run npm run build.
Any ideas?
Thanks in advance!
My team had similar issues as you are describing. We could fix it by adding the optimization object to our Webpack config (vue.config.js`).
const {defineConfig} = require('#vue/cli-service');
module.exports = defineConfig({
/* your config */
configureWebpack: {
optimization: {
runtimeChunk: 'single',
},
},
devServer: {
// we need this for apollo to work properly
proxy: `https://${process.env.SANDBOX_HOSTNAME}/`,
host: '0.0.0.0',
allowedHosts: 'all',
},
});
The optimization part fixed the HMR for us. However, if you're using Firefox, your console might still be spammed by error messages like these:
The connection to wss://SANDBOX_HOSTNAME:8080/ws was interrupted while
the page was loading.
This has been a blocker of vue 3 for us, so I hope it helps. ✌️

post request not working in express app deployed in kubernetes locally with minikube

when I request post handler in the express app it returns Cannot POST / but the post handler is defined in there. When is run this app through docker-compose it worlds perfectly but not in Kubernetes cluster using minikube. Here is the express app code.
const keys = require('./keys');
// Express App Setup
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(bodyParser.json());
// Postgres Client Setup
const { Pool, Client } = require('pg');
const pgClient = new Pool({
user: keys.pgUser,
host: keys.pgHost,
database: keys.pgDatabase,
password: keys.pgPassword,
port: keys.pgPort
});
pgClient.on('error', () => console.log('Lost PG connection'));
pgClient
.query('CREATE TABLE IF NOT EXISTS values (number INT)')
.catch(err => console.log(err));
// Redis Client Setup
const redis = require('redis');
const redisClient = redis.createClient({
host: keys.redisHost,
port: keys.redisPort,
retry_strategy: () => 1000
});
const redisPublisher = redisClient.duplicate();
// Express route handlers
app.get('/', (req, res) => {
res.send('Hi');
});
app.get('/values/all', async (req, res) => {
const {rows} = await pgClient.query('SELECT * from values');
console.log('DATA IN POSTGRES', rows)
res.send(rows);
});
app.get('/values/current', async (req, res) => {
redisClient.hgetall('values', (err, values) => {
res.send(values);
});
});
app.post('/data', (req,res) => {
res.send(req.body.data)
})
app.post('/values', (req, res) => {
console.log("FORM DATA", req.body)
const index = req.body.index;
if (parseInt(index) > 40) {
return res.status(422).send('Index too high');
}
redisClient.hset('values', index, 'Nothing yet!');
redisPublisher.publish('insert', index);
pgClient.query('INSERT INTO values(number) VALUES($1)', [index], (err,ress) => {
if(err){
console.log("PG ERROR ON INSERT")
} else {
console.log('PG DATA', ress.rows[0])
res.send({ working: true });
}
});
});
app.listen(5000, err => {
console.log('Listening');
});
Here is the server deployment config
apiVersion: apps/v1
kind: Deployment
metadata:
name: server-deployment
spec:
replicas: 3
selector:
matchLabels:
component: server
template:
metadata:
labels:
component: server
spec:
containers:
- name: server
image: rajneesh4736/multi-server:v4.0.3
ports:
- containerPort: 5000
env:
- name: REDIS_HOST
value: redis-cluster-ip-service
- name: REDIS_PORT
value: "6379"
- name: PGUSER
value: postgres
- name: PGHOST
value: postgres-cluster-ip-service
- name: PGPORT
value: "5432"
- name: PGDATABASE
value: postgres
- name: PGPASSWORD
valueFrom:
secretKeyRef:
name: pgpassword
key: PGPASSWORD
Here is the server cluster IP config
apiVersion: v1
kind: Service
metadata:
name: server-cluster-ip-service
spec:
type: ClusterIP
selector:
component: server
ports:
- port: 5000
targetPort: 5000

Actioncable works locally but not after deploying to Heroku - Rails & React

I am using actioncable for a chat feature. It works perfectly when I test locally, but when I deploy to Heroku I get this error:
'WebSocket connection to 'wss://dg-automotive-portal-
rails.herokuapp.com/cable' failed: Error during WebSocket handshake: Unexpected response code: 404'
production.rb:
config.action_cable.url = 'wss://dg-automotive-portal-
rails.herokuapp.com/cable'
config.action_cable.allowed_request_origins = [
'https://dg-automotive-portal.herokuapp.com/', 'http://dg-
automotive-portal.herokuapp.com/' ]
cable.yml:
production:
adapter: redis
url:redis:MYURL
routes.rb has
mount ActionCable.server => '/cable'
And I have the redis gem installed. Does anyone know why this doesn't work when I deploy?
Javascript code called on componentWillMount:
createSocket() {
let cable = Cable.createConsumer('wss://dg-automotive-portal-rails.herokuapp.com/cable')
this.chats = cable.subscriptions.create({
channel: 'ChatChannel'
}, {
connected: () => {
console.log("connected!")
},
received: (data) => {
this.setState({
chatLogs: [...this.state.chatLogs, data]
})
},
create: function(chatContent, datetime, currentUser) {
this.perform('create', {
content: chatContent,
time: datetime,
user_id: currentUser
})
}
})
}

TypeORM connection provider as Connection class

Is it possible to use connection class as provide like here?
import { Connection, createConnection } from 'typeorm';
export const databaseProviders = [{
provide: Connection,
useFactory: async () => await createConnection({
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'testo',
entities: [
__dirname + '/../**/*.entity{.ts,.js}',
],
logging: true,
synchronize: true,
}),
}];
To make imports work like:
constructor(
private connection: Connection,
) {
this.repository = connection.getRepository(Project);
}
In that case nestjs can't find dependency. I guess the problem is in typeorm, it is compiled to plain es5 function. But maybe there a solution for this?
repository to reproduce
UPDATE:
I found acceptable solution nestjs typeorm module, but don't understand why my Connection class is not worked, but it works well with strings. Hope #kamil-myśliwiec will help to understand.
modules: [
TypeOrmModule.forRoot(
[
Build,
Project,
],
{
type: 'postgres',
host: 'localhost',
port: 5432,
username: 'postgres',
password: 'postgres',
database: 'testo',
entities: [
Build,
],
logging: true,
synchronize: true,
}),
],
// And the n inject like this by entity name
#InjectRepository(Build) private repository: Repository<Build>,

Resources