Skip to content
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
7 changes: 2 additions & 5 deletions lib/StorageError.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,11 @@ const Updater = createUpdater(
messages
)

const E = ErrorWrapper(
'WebStorageError',
'WebLib',
Updater
)
const E = ErrorWrapper('WebStorageError', 'WebLib', Updater)

E('ERROR_INVALID_HEADER_NAME', '`%s` is not a valid response header name')
E('ERROR_INVALID_HEADER_VALUE', '`%s` is not a valid response header value for `%s`')
E('ERROR_CACHE_INVALIDATION', 'Failed to invalidate cache: %s')

function logAndThrow (e) {
logger.error(JSON.stringify(e, null, 2))
Expand Down
33 changes: 33 additions & 0 deletions lib/invalidate-cache.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
Copyright 2025 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
const { createFetch } = require('@adobe/aio-lib-core-networking')
const { codes, logAndThrow } = require('./StorageError')

module.exports = async function invalidateCache (deployApiHost, namespace, tokenHeader) {
const fetch = createFetch()

const url = `https://${deployApiHost}/cdn-api/namespaces/${namespace}/cache`
try {
const response = await fetch(url, {
method: 'DELETE',
headers: {
Authorization: tokenHeader
}
})
if (!response.ok) {
logAndThrow(new codes.ERROR_CACHE_INVALIDATION({ messageValues: [`${url} ${response.status} ${response.statusText} ${await response.text()}`], sdkDetails: {} }))
}
return response.json()
} catch (error) {
logAndThrow(new codes.ERROR_CACHE_INVALIDATION({ messageValues: [`${url} ${error.message}`], sdkDetails: {} }))
}
}
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
"dependencies": {
"@adobe/aio-lib-core-config": "^5",
"@adobe/aio-lib-core-logging": "^3",
"@adobe/aio-lib-core-networking": "^5.0.4",
"@adobe/aio-lib-core-tvm": "^4",
"@adobe/aio-lib-env": "^3.0.1",
"@aws-sdk/client-s3": "^3.624.0",
"@smithy/node-http-handler": "^4.0.2",
"core-js": "^3.25.1",
Expand Down
17 changes: 16 additions & 1 deletion src/deploy-web.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/*
Copyright 2020 Adobe. All rights reserved.
Copyright 2025 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0
Expand All @@ -12,6 +12,7 @@ governing permissions and limitations under the License.

const RemoteStorage = require('../lib/remote-storage')
const getS3Credentials = require('../lib/getS3Creds')
const invalidateCache = require('../lib/invalidate-cache')

const fs = require('fs-extra')
const path = require('path')
Expand All @@ -21,6 +22,10 @@ const deployWeb = async (config, log) => {
throw new Error('cannot deploy web, app has no frontend or config is invalid')
}

if (!config.web.namespace || !config.web.apihost || !config.web.auth_handler) {
throw new Error('cannot deploy web, config is missing "web.namespace", "web.apihost", or "web.auth_handler" fields')
}

/// build files
const dist = config.web.distProd
if (!fs.existsSync(dist) ||
Expand All @@ -30,6 +35,16 @@ const deployWeb = async (config, log) => {
throw new Error(`missing files in ${dist}, maybe you forgot to build your UI ?`)
}

/// deploy
// 1. invalidate cache

// this will trigger a login
const authHeader = await config.web.auth_handler()
const namespace = config.web.namespace
const apihost = config.web.apihost // this is the deploy service apihost
await invalidateCache(apihost, namespace, authHeader)

// 2. upload files
const creds = await getS3Credentials(config)

const remoteStorage = new RemoteStorage(creds)
Expand Down
75 changes: 75 additions & 0 deletions test/lib/invalidate-cache.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
/*
Copyright 2025 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

jest.mock('@adobe/aio-lib-core-networking', () => ({
createFetch: jest.fn()
}))

const { createFetch } = require('@adobe/aio-lib-core-networking')
const invalidateCache = require('../../lib/invalidate-cache')

describe('invalidate-cache', () => {
beforeEach(() => {
jest.clearAllMocks()
})

test('succeeds when API returns ok', async () => {
const mockJson = { status: 'ok' }
const mockFetch = jest.fn(async () => ({ ok: true, json: async () => mockJson }))
createFetch.mockReturnValue(mockFetch)

const host = 'deploy.example.com'
const ns = 'my-ns'
const header = 'Bearer token'

await expect(invalidateCache(host, ns, header)).resolves.toEqual(mockJson)
expect(mockFetch).toHaveBeenCalledWith(`https://${host}/cdn-api/namespaces/${ns}/cache`, expect.objectContaining({
method: 'DELETE',
headers: { Authorization: header }
}))
})

test('throws wrapped error when response not ok', async () => {
const mockFetch = jest.fn(async () => ({
ok: false,
status: 500,
statusText: 'Internal Server Error',
text: async () => 'boom'
}))
createFetch.mockReturnValue(mockFetch)

const host = 'deploy.example.com'
const ns = 'my-ns'
const header = 'Bearer token'

await expect(() => invalidateCache(host, ns, header)).toThrowWithMessageContaining([
'[WebLib:ERROR_CACHE_INVALIDATION]',
'failed to invalidate cache',
'500'
])
})

test('throws wrapped error when network fails', async () => {
const mockFetch = jest.fn(async () => { throw new Error('network down') })
createFetch.mockReturnValue(mockFetch)

const host = 'deploy.example.com'
const ns = 'my-ns'
const header = 'Bearer token'

await expect(() => invalidateCache(host, ns, header)).toThrowWithMessageContaining([
'[WebLib:ERROR_CACHE_INVALIDATION]',
'failed to invalidate cache',
'network down'
])
})
})
76 changes: 68 additions & 8 deletions test/src/deploy-web.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ governing permissions and limitations under the License.

const { vol } = global.mockFs()
const deployWeb = require('../../src/deploy-web')
jest.mock('../../lib/invalidate-cache')
const invalidateCache = require('../../lib/invalidate-cache')
const fs = require('fs-extra')
jest.mock('fs-extra')

Expand All @@ -38,6 +40,7 @@ describe('deploy-web', () => {
mockRemoteStorageInstance.folderExists.mockReset()
mockRemoteStorageInstance.uploadDir.mockReset()
getS3Credentials.mockClear()
invalidateCache.mockReset()

global.cleanFs(vol)
})
Expand All @@ -48,6 +51,13 @@ describe('deploy-web', () => {
await expect(deployWeb({ app: { hasFrontEnd: false } })).rejects.toThrow('cannot deploy web')
})

test('throws if web config missing required fields', async () => {
const base = { app: { hasFrontend: true } }
await expect(deployWeb({ ...base, web: {} })).rejects.toThrow('config is missing "web.namespace", "web.apihost", or "web.auth_handler"')
await expect(deployWeb({ ...base, web: { namespace: 'ns' } })).rejects.toThrow('config is missing "web.namespace", "web.apihost", or "web.auth_handler"')
await expect(deployWeb({ ...base, web: { namespace: 'ns', apihost: 'deploy.example.com' } })).rejects.toThrow('config is missing "web.namespace", "web.apihost", or "web.auth_handler"')
})

test('throws if src dir does not exist', async () => {
const config = {
s3: {
Expand All @@ -57,7 +67,10 @@ describe('deploy-web', () => {
hasFrontend: true
},
web: {
distProd: 'dist'
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
await expect(deployWeb(config)).rejects.toThrow('missing files in dist')
Expand All @@ -72,7 +85,10 @@ describe('deploy-web', () => {
hasFrontend: true
},
web: {
distProd: 'dist'
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
fs.existsSync.mockReturnValue(true)
Expand All @@ -89,7 +105,10 @@ describe('deploy-web', () => {
hasFrontend: true
},
web: {
distProd: 'dist'
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
fs.existsSync.mockReturnValue(true)
Expand All @@ -114,13 +133,17 @@ describe('deploy-web', () => {
hostname: 'host'
},
web: {
distProd: 'dist'
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
fs.existsSync.mockReturnValue(true)
fs.lstatSync.mockReturnValue({ isDirectory: () => true })
fs.readdirSync.mockReturnValue({ length: 1 })
await expect(deployWeb(config)).resolves.toEqual('https://ns.host/index.html')
expect(invalidateCache).toHaveBeenCalledWith('deploy.example.com', 'ns', 'Bearer token')
expect(getS3Credentials).toHaveBeenCalledWith(config)
expect(RemoteStorage).toHaveBeenCalledWith('fakecreds')
expect(mockRemoteStorageInstance.uploadDir).toHaveBeenCalledWith('dist', 'somefolder', config, null)
Expand All @@ -144,7 +167,10 @@ describe('deploy-web', () => {
hostname: 'host'
},
web: {
distProd: 'dist'
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
fs.existsSync.mockReturnValue(true)
Expand All @@ -154,6 +180,7 @@ describe('deploy-web', () => {
// for func coverage
mockRemoteStorageInstance.uploadDir.mockImplementation((a, b, c, func) => func('somefile'))
await expect(deployWeb(config, mockLogger)).resolves.toEqual('https://ns.host/index.html')
expect(invalidateCache).toHaveBeenCalledWith('deploy.example.com', 'ns', 'Bearer token')
expect(getS3Credentials).toHaveBeenCalledWith(config)
expect(RemoteStorage).toHaveBeenCalledWith('fakecreds')
expect(mockRemoteStorageInstance.uploadDir).toHaveBeenCalledWith('dist', 'somefolder', config, expect.any(Function))
Expand All @@ -176,7 +203,10 @@ describe('deploy-web', () => {
hostname: 'host'
},
web: {
distProd: 'dist'
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
fs.existsSync.mockReturnValue(true)
Expand All @@ -187,6 +217,7 @@ describe('deploy-web', () => {
mockRemoteStorageInstance.folderExists.mockResolvedValue(true)

await expect(deployWeb(config, mockLogger)).resolves.toEqual('https://ns.host/index.html')
expect(invalidateCache).toHaveBeenCalledWith('deploy.example.com', 'ns', 'Bearer token')
expect(getS3Credentials).toHaveBeenCalledWith(config)
expect(mockLogger).toHaveBeenCalledWith('warning: an existing deployment will be overwritten')
expect(RemoteStorage).toHaveBeenCalledWith('fakecreds')
Expand All @@ -210,7 +241,10 @@ describe('deploy-web', () => {
hostname: 'host'
},
web: {
distProd: 'dist'
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
fs.existsSync.mockReturnValue(true)
Expand All @@ -220,13 +254,36 @@ describe('deploy-web', () => {
mockRemoteStorageInstance.folderExists.mockResolvedValue(true)

await expect(deployWeb(config)).resolves.toEqual('https://ns.host/index.html')
expect(invalidateCache).toHaveBeenCalledWith('deploy.example.com', 'ns', 'Bearer token')
expect(getS3Credentials).toHaveBeenCalledWith(config)
expect(mockRemoteStorageInstance.folderExists).toHaveBeenCalledWith('somefolder/')
expect(mockRemoteStorageInstance.uploadDir).toHaveBeenCalledWith('dist', 'somefolder', config, null)
// empty dir!
expect(mockRemoteStorageInstance.emptyFolder).toHaveBeenCalledWith('somefolder/')
})

test('invalidates cache', async () => {
const config = {
ow: { namespace: 'ns', auth: 'password' },
s3: { folder: 'somefolder' },
app: { hasFrontend: true, hostname: 'host' },
web: {
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
fs.existsSync.mockReturnValue(true)
fs.lstatSync.mockReturnValue({ isDirectory: () => true })
fs.readdirSync.mockReturnValue({ length: 1 })
mockRemoteStorageInstance.folderExists.mockResolvedValue(false)
invalidateCache.mockResolvedValue({ status: 'ok' })

await expect(deployWeb(config)).resolves.toEqual('https://ns.host/index.html')
expect(invalidateCache).toHaveBeenCalledWith('deploy.example.com', 'ns', 'Bearer token')
})

test('calls to s3 should use ending slash', async () => {
const config = {
ow: {
Expand All @@ -243,7 +300,10 @@ describe('deploy-web', () => {
hostname: 'host'
},
web: {
distProd: 'dist'
distProd: 'dist',
auth_handler: jest.fn(async () => 'Bearer token'),
namespace: 'ns',
apihost: 'deploy.example.com'
}
}
const emptyFolder = jest.fn()
Expand Down