Failed to register a ServiceWorker for scope ('https://*.com/') with script ('https://*.com/service-worker.js'): Failed to access storage - service-worker

Why might the error happen: "Failed to register a ServiceWorker for scope ('https://.com/') with script ('https://.com/service-worker.js'): Failed to access storage."?
service-worker.js code:
self.addEventListener('install', function() {
self.skipWaiting();
});
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});

Related

AWS CodeBuild With the CDK "Error: .git/HEAD does not exist"

My desire is to build the CDK Cloud Formation stacks using AWS Code Pipeline, from the CDK library aws-cdk-lib/pipelines. When running cdk ls in the CLI, everything works as expected. I can successfully deploy the pipeline as well with cdk deploy.
Error Message:
[Container] 2022/12/30 09:18:36 Running command npx cdk synth
Error: .git/HEAD does not exist
at gitHeadPath (/codebuild/output/src224694107/src/backend/node_modules/git-branch/index.js:36:11)
at branch (/codebuild/output/src224694107/src/backend/node_modules/git-branch/index.js:14:28)
at /codebuild/output/src224694107/src/backend/src/context/getContext.ts:11:41
at new Promise (<anonymous>)
at Object.exports.getContext (/codebuild/output/src224694107/src/backend/src/context/getContext.ts:9:12)
at createStack (/codebuild/output/src224694107/src/backend/bin/template.ts:9:25)
at Object.<anonymous> (/codebuild/output/src224694107/src/backend/bin/template.ts:18:1)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Module.m._compile (/codebuild/output/src224694107/src/backend/node_modules/ts-node/src/index.ts:1618:23)
at Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
(node:179) UnhandledPromiseRejectionWarning: undefined
(Use `node --trace-warnings ...` to show where the warning was created)
(node:179) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:179) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
CDK Pipeline Code:
this.codePipeline = new CodePipeline(this, `${environment}-pipeline-${appName}`, {
pipelineName: `${environment}-pipeline-${appName}`,
selfMutation: true,
crossAccountKeys: false,
role: this.codePipelineRole,
synth: new ShellStep("Deployment", {
input: CodePipelineSource.codeCommit(this.codeRepository, environment),
installCommands: ["npm uninstall -g aws-cdk", "npm i -g npm#latest", "npm install -g aws-cdk"],
commands: ["cd backend", "npm ci", "npm run build", "npx cdk synth"],
primaryOutputDirectory: "backend/cdk.out",
}),
});
getContext Function:
export const getContext = (app: App): Promise<CDKContext> => {
return new Promise(async (resolve, reject) => {
try {
const currentBranch = await gitBranch();
const environment = app.node.tryGetContext("environments").find((e: any) => e.branchName === currentBranch);
const globals = app.node.tryGetContext("globals");
return resolve({...globals, ...environment});
}
catch (error) {
console.error("error", error);
return reject();
}
})
}
Package.json dependencies:
"dependencies": {
"#aws-cdk/aws-appsync-alpha": "^2.55.1-alpha.0",
"aws-cdk-lib": "^2.58.0",
"aws-sdk": "^2.1278.0",
"constructs": "^10.1.204",
"git-branch": "^2.0.1",
"source-map-support": "^0.5.21"
}
Code Build has two options for cloning repositories:
CodePipeline Default - "AWS CodePipeline uses the default zip format for artifacts in the pipeline. Does not include git metadata about the repository"
Full Clone - "AWS CodePipeline passes metadata about the repository that allows subsequent actions to do a full git clone. Only supported for AWS CodeBuild actions."
Quotes taken from the console.
Therefore, the pipeline definition needed to add a Code Commit source prop to tell the CDK to do a full clone. CDK Docs for options here.
Updating the input:
input: CodePipelineSource.codeCommit(this.codeRepository, environment, {
codeBuildCloneOutput: true
})
codeBuildCloneOutput - "If this is set, the next CodeBuild job clones the repository (instead of CodePipeline downloading the files)." This allows for a full clone of the repository, and will remove the error.
CDK Permissions Update:
This image shows now the CodeBuild can do a GitPull:

What url should I use to make a request to the container from the browser during development?

I have two services, a client and a server. I am using Next.js and React on the client and express for my server. And I have a docker-compose file. I need to implement some endpoints on the backend and make requests from the client to the backend using axios.
During development I am running docker-compose up. While working on the app I created an address form in the client and wanted to see the results in the browser. When I try to submit the form and send the request to the server I am getting 404. This is the code in the client that makes a request to the backend:
import axios from 'axios'
const postNewAddress = async (address) => {
axios.post('/address', address)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
module.exports = {
postNewAddress
}
And this is what I currently have on the backend:
const express = require( 'express' );
const app = express();
const port = process.env.PORT || 3001
app.use(express.json())
app.get( '/', ( req, res ) => {
res.send({ greeting: 'Hello world!' });
});
app.post('/address', ( req, res ) => {
const address = req.body
console.log(address)
res.json(address)
})
app.listen(port, err => {
if (err) throw err;
console.log(`Listening on PORT ${port}!`)
})
When I change the URL to http://server:3001/address in axios request, I am getting net::ERR_NAME_NOT_RESOLVED error. I did some research and that happens probably because the browser and docker containers are running in different networks. But I couldn't find any solution that would allow me to make requests to container from a browser.
Here is the gist for docker-compose.yml
Docker compose file
Let's say you have one property in variable address with which post request was made.
address = { 'id': 123 };
Now to fetch that in your backend code you need to do something like this
app.post('/address', ( req, res ) => {
const id = req.body.id
console.log(id)
res.json(id)
})
Browser applications can never use the Docker-container hostnames. Even if the application is being served from an inside Docker, it ultimately runs from inside the browser, and outside Docker space.
If this is a development system, so the backend container and your development environment are on the same system, you can generally connect to localhost and the published ports: of your container. If your docker-compose.yml declares ports: [3001:3001] for the backend, then you can connect to http://localhost:3001/address.
You can also set this address in the Webpack dev server proxy configuration, so the /address relative URL you have in your code now continues to work.

TestCafe docker- unable to run tests using runner class

I have all my tests running in a docker container and it works fine. Since I have a few test files which need concurrent tests and a file which doesn't need a concurrent test that is the reason I need to create a test runner to run my tests. Here is what my test runner class looks like:
const createTestCafe = require('testcafe');
let testcafe = null;
createTestCafe('localhost', 1337, 1338)
.then((tc) => {
testcafe = tc;
const runner1 = testcafe.createRunner();
const runner2 = testcafe.createRunner();
const promise1 = runner1
.src(['/tests/uitests/**/conctests/accounttest.js', '/tests/uitests/**/conctests/dashtest.js'])
.browsers('chromium')
.screenshots({ takeOnFails: true })
.reporter(['spec', {
name: 'html',
output: 'resultsrunner1.html' }, {
name: 'xunit',
output: 'res1.xml',
}])
.concurrency(3)
.run({
skipJsErrors: true,
quarantineMode: true,
});
const promise2 = runner2
.src('/tests/uitests/**/conctests/roletest.js')
.browsers('chromium')
.screenshots({ takeOnFails: true })
.reporter(['spec', {
name: 'html',
output: 'resultsrunner2.html' }, {
name: 'xunit',
output: 'res2.xml',
}])
.run({
skipJsErrors: true,
quarantineMode: true,
});
return Promise.all([promise1, promise2]);
})
.then(() => {
testcafe.close();
process.exit();
})
.catch((err) => {
console.log(err);
testcafe.close();
process.exit(1);
});
when I run it using the command:
docker run --net=host -v `pwd`:/tests -it --entrypoint node testcafe /tests/testrunner.js
I get this error:
Error: Unable to establish one or more of the specified browser connections. This can be caused by network issues or remote device failure.
at /tests/node_modules/testcafe/src/runner/browser-set.js:84:30
at Generator.next (<anonymous>)
at step (/tests/node_modules/babel-runtime/helpers/asyncToGenerator.js:17:30)
at /tests/node_modules/babel-runtime/helpers/asyncToGenerator.js:35:14
at new Promise (<anonymous>)
at new F (/tests/node_modules/core-js/library/modules/_export.js:36:28)
at /tests/node_modules/babel-runtime/helpers/asyncToGenerator.js:14:12
at BrowserSet._waitConnectionsOpened (/tests/node_modules/testcafe/src/runner/browser-set.js:77:37)
at _waitConnectionsOpened (/tests/node_modules/testcafe/src/runner/browser-set.js:107:35)
at invokeCallback (/tests/node_modules/pinkie/index.js:60:12)
at Array.forEach (<anonymous>)
at publish (/tests/node_modules/pinkie/index.js:147:32)
at Array.publishFulfillment (/tests/node_modules/pinkie/index.js:152:2)
at Immediate.asyncFlush (/tests/node_modules/pinkie/index.js:17:19)
at runCallback (timers.js:706:11)
at tryOnImmediate (timers.js:676:5)
at processImmediate (timers.js:658:5)
at process.topLevelDomainCallback (domain.js:126:23)
I tried firefox and chromium --no-sandbox as well but nothing worked for me. In my case, I'm using the existing available browser image from the TestCafe. Please suggest as all my tests are stuck right now.
Try to use a headless browser. If you need to run tests with the browser UI, perform this step in your runner to initialize the in-memory display server.

Grunt browserSync grunt-php does not reload PHP files on change

I am using Grunt + browserSync + grunt-php. The server starts normally. The problem is that whenever I make changes to PHP files, the changes are not reloaded automatically in browser. I have to manually reload the page despite having the settings in place. Been trying to solve this issue for the past 1 week, but no success. Tried out other online sources, but didn't help either. Please help.
Directory structure:
my_app/
src/
index.php
about.php
dist/
Gruntfile.js:
"use strict";
module.exports = function (grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
watch: {
php: {
files: ['src/**/*.php']
}
},
browserSync: {
dev: {
bsFiles: {
src: 'src/**/*.php'
},
options: {
proxy: '127.0.0.1:8010', //our PHP server
port: 8080, // our new port
open: true,
watchTask: true
}
}
},
php: {
dev: {
options: {
port: 8010,
base: 'src'
}
}
}
});
grunt.registerTask('default', [
'php', // Using the PHP instance as a proxy
'browserSync',
'watch' // Any other watch tasks you want to run
]);
};
A kind soul helped me with the answer. I don't take credit for the answer and would like to share the solution so that it may help someone in need. Here it is:
1) Just make sure that you have the body tag in the PHP file that you want to reload.
2) Include the following JS code in the page:
<script id="__bs_script__">
//<![CDATA[
document.write("<script async src='/browser-sync/browser-sync-client.js?v=2.17.5'><\/script>".replace("HOST", location.hostname));
//]]>
</script>

how to catch the exit event of process in docker

I create a process with nodejs on docker container, but I don't catch the exit event of the process, the docker version is 1.0.1, but the same code is okay on the version 0.91 of docker.
var spawn = require('child_process').spawn;
var exec = spawn('docker', 'run busybox /etc/bin/bash each hello world');
exec.on('error', function(err){
console.log(err);
});
exec.stdout.on('data', function(data) {
console.log('stdout: ' + data);
});
exec.on('exit', function(err){
console.log('exit')
});
I think the problem is in the use of spawn. The second parameter should be an array according to the nodejs docs.
In a quick test, your code launches docker without any arguments, at least on node v0.10.28.

Resources