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

fix: polished after doc review #51

Merged
merged 25 commits into from
May 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
d5fa4a2
feat: add customize error message
nicolasalexandre9 May 3, 2024
c912a34
feat: add prefix config
nicolasalexandre9 May 3, 2024
c42ec9d
feat: add config key customize_error_message
nicolasalexandre9 May 3, 2024
b0c5524
chore: update config
nicolasalexandre9 May 3, 2024
4b8ec61
fix: prefix
nicolasalexandre9 May 14, 2024
7f3f1fb
feat: serialize logger and customize_error_message proc
nicolasalexandre9 May 14, 2024
c5d7f69
feat: update loading gem and install
nicolasalexandre9 May 15, 2024
d0826fb
fix: action permissions
nicolasalexandre9 May 16, 2024
7d6f872
fix: action form
nicolasalexandre9 May 16, 2024
aa5217e
fix: condition tree leaf
nicolasalexandre9 May 16, 2024
f782a5c
fix: emulate field operator
nicolasalexandre9 May 17, 2024
32e2064
fix: sort
nicolasalexandre9 May 17, 2024
54daf70
feat: add validations
nicolasalexandre9 May 17, 2024
cff4093
feat: update hooks keys
nicolasalexandre9 May 20, 2024
704f22d
fix: segments and pagination
nicolasalexandre9 May 20, 2024
b9fecdd
fix: agent customize collection function
nicolasalexandre9 May 21, 2024
bf289af
fix: aggregate and count route
nicolasalexandre9 May 21, 2024
1ce2a9b
fix: serialize relationships
nicolasalexandre9 May 21, 2024
38546be
fix: tests
nicolasalexandre9 May 22, 2024
604a4b2
fix: charts api
nicolasalexandre9 May 22, 2024
0fe3068
feat: add logs on sse cache invalidation
nicolasalexandre9 May 22, 2024
f66c1db
fix: generator field
nicolasalexandre9 May 22, 2024
2ceaa1c
fix: remove useless todo
nicolasalexandre9 May 22, 2024
7e307d1
fix: tests
nicolasalexandre9 May 22, 2024
0a5f297
fix: lint
nicolasalexandre9 May 23, 2024
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
16 changes: 16 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
Expand Up @@ -279,3 +279,19 @@ Layout/LineLength:
RSpec/MultipleMemoizedHelpers:
Max: 10

Security/Eval:
Exclude:
- 'packages/forest_admin_agent/lib/forest_admin_agent/http/error_handling.rb'
- 'packages/forest_admin_agent/lib/forest_admin_agent/services/logger_service.rb'

Style/PercentLiteralDelimiters:
Exclude:
- 'packages/forest_admin_rails/lib/generators/forest_admin_rails/install_generator.rb'

Lint/InterpolationCheck:
Exclude:
- 'packages/forest_admin_rails/lib/generators/forest_admin_rails/install_generator.rb'

Lint/UnusedMethodArgument:
Exclude:
- 'packages/forest_admin_rails/config/initializers/forest_admin_error_subscriber.rb'
1 change: 0 additions & 1 deletion agent_ruby.gemspec
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,5 @@ repository (monorepo) for the Ruby agent."
end
end

spec.executables = ["run_rspec"]
spec.require_paths = ["lib"]
end
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ def add_chart(name, &definition)

def customize_collection(name, &handle)
@customizer.customize_collection(name, handle)

self
end

def build
Expand Down Expand Up @@ -74,6 +76,14 @@ def build_cache
return unless @has_env_secret

cache = @container.resolve(:cache)
@options[:customize_error_message] = @options[:customize_error_message]
&.source
&.strip
&.delete_prefix('config.customize_error_message =')
&.strip

@options[:logger] = @options[:logger]&.source&.strip&.delete_prefix('config.logger =')&.strip

cache.set('config', @options.to_h)
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ def self.instance
end

def self.datasource
instance.resolve(:datasource)
instance.resolve(:datasource) do
ForestAdminDatasourceToolkit::Datasource.new
end
end

def self.logger
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,12 @@ module ForestAdminAgent
module Http
module Exceptions
class AuthenticationOpenIdClient < HttpException
attr_reader :error, :error_description, :state
attr_reader :error, :message, :state

def initialize(error, error_description, state)
super(error, 401, error_description)
@error = error
@error_description = error_description
@message = error_description
@state = state
end
end
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
module ForestAdminAgent
module Http
module ErrorHandling
def get_error_message(error)
if error.respond_to?(:ancestors) && error.ancestors.include?(ForestAdminAgent::Http::Exceptions::HttpException)
return error.message
end

if (customizer = ForestAdminAgent::Facades::Container.cache(:customize_error_message))
message = eval(customizer).call(error)
return message if message
end

'Unexpected error'
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ def handle_hook_request(args = {})
data,
filter,
{
change_field: nil,
change_field: args.dig(:params, :data, :attributes, :changed_field),
search_field: nil,
search_values: {},
includeHiddenFields: false
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,26 @@ def setup_routes
"forest_chart_get_#{slug}",
'get',
"/_charts/#{slug}",
proc { handle_smart_chart }
proc { |args| handle_smart_chart(args) }
)

add_route(
"forest_chart_post_#{slug}",
'post',
"/_charts/#{slug}",
proc { handle_api_chart }
proc { |args| handle_api_chart(args) }
)

unless Facades::Container.cache(:is_production)
Facades::Container.logger.log('Info', "/forest/_charts/#{slug}")
Facades::Container.logger.log('Info', "Chart #{@chart_name} was mounted at /forest/_charts/#{slug}")
end

self
end

def handle_api_chart
def handle_api_chart(args = {})
@caller = Utils::QueryStringParser.parse_caller(args)

{
content: Serializer::ForestChartSerializer.serialize(
@datasource.render_chart(
Expand All @@ -48,7 +50,9 @@ def handle_api_chart
}
end

def handle_smart_chart
def handle_smart_chart(args = {})
@caller = Utils::QueryStringParser.parse_caller(args)

{
content: @datasource.render_chart(
@caller,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ def handle_request(args = {})
]),
page: ForestAdminAgent::Utils::QueryStringParser.parse_pagination(args),
search: ForestAdminAgent::Utils::QueryStringParser.parse_search(@collection, args),
search_extended: ForestAdminAgent::Utils::QueryStringParser.parse_search_extended(args)
search_extended: ForestAdminAgent::Utils::QueryStringParser.parse_search_extended(args),
sort: ForestAdminAgent::Utils::QueryStringParser.parse_sort(@collection, args),
segment: ForestAdminAgent::Utils::QueryStringParser.parse_segment(@collection, args)
)

projection = ForestAdminAgent::Utils::QueryStringParser.parse_projection_with_pks(@collection, args)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def handle_request(args = {})
return {
name: @child_collection.name,
content: {
count: result[0][:value]
count: result.empty? ? 0 : result[0]['value']
}
}
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def initialize(object, options = nil)
end

def base_url
Facades::Container.cache(:prefix)
'/forest'
end

def type
Expand Down Expand Up @@ -177,11 +177,11 @@ def relationships
end

def relationship_self_link(attribute_name)
"/#{self_link}/relationships/#{format_name(attribute_name)}"
"#{self_link}/relationships/#{format_name(attribute_name)}"
end

def relationship_related_link(attribute_name)
"/#{self_link}/#{format_name(attribute_name)}"
"#{self_link}/#{format_name(attribute_name)}"
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,11 @@ def initialize(logger_level = 'Info', logger = nil)
@logger_level = logger_level
@logger = logger
@default_logger = MonoLogger.new($stdout)
# TODO: HANDLE FORMATTER
end

def log(level, message)
if @logger
@logger.call(get_level(level), message)
eval(@logger).call(get_level(level), message)
else
@default_logger.add(get_level(level), message)
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def can_smart_action?(request, collection, filter, allow_fetch: true)
filter
)

smart_action_approval.can_execute?
is_allowed = smart_action_approval.can_execute?
ForestAdminAgent::Facades::Container.logger.log(
'Debug',
"User #{user_data[:roleId]} is #{is_allowed ? "" : "not"} allowed to perform #{action["name"]}"
Expand Down Expand Up @@ -213,7 +213,8 @@ def permission_system?
end[:enable]
end

def find_action_from_endpoint(collection_name, endpoint, http_method)
def find_action_from_endpoint(collection_name, path, http_method)
endpoint = path.partition('/forest/')[1..].join
schema_file = JSON.parse(File.read(Facades::Container.config_from_cache[:schema_path]))
actions = schema_file['collections']&.select { |collection| collection['name'] == collection_name }&.first&.dig('actions')

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,30 @@ def self.run

MESSAGE_CACHE_KEYS[event.type]&.each do |cache_key|
Permissions.invalidate_cache(cache_key)
# TODO: HANDLE LOGGER
# "info","invalidate cache {MESSAGE_CACHE_KEYS[event.type]} for event {event.type}"
ForestAdminAgent::Facades::Container.logger.log(
'Info',
"invalidate cache #{MESSAGE_CACHE_KEYS[event.type]} for event #{event.type}"
)
end
# TODO: HANDLE LOGGER add else
# "info", "SSECacheInvalidation: unhandled message from server: {event.type}"

ForestAdminAgent::Facades::Container.logger.log(
'Info',
"SSECacheInvalidation: unhandled message from server: #{event.type}"
)
end
end
rescue StandardError
ForestAdminAgent::Facades::Container.logger.log(
'Debug',
'SSE connection to forestadmin server'
)

ForestAdminAgent::Facades::Container.logger.log(
'Warning',
'SSE connection to forestadmin server closed unexpectedly, retrying.'
)

raise ForestException, 'Failed to reach SSE data from ForestAdmin server.'
# TODO: HANDLE LOGGER
# "debug", "SSE connection to forestadmin server due to ..."
# "warning", "SSE connection to forestadmin server closed unexpectedly, retrying."
end
end
end
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def self.unpack_id(collection, packed_id, with_key: false)
field = collection.schema[:fields][pk_name]
value = primary_key_values[index]
casted_value = field.column_type == 'Number' ? value.to_i : value
# TODO: call FieldValidator::validateValue($value, $field, $castedValue);
ForestAdminDatasourceToolkit::Validations::FieldValidator.validate_value(value, field, casted_value)

[pk_name, casted_value]
end.to_h
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,16 +23,16 @@ def self.parse_condition_tree(collection, args)
return if filters.nil?

filters = JSON.parse(filters, symbolize_names: true) if filters.is_a? String
# TODO: add else for convert all keys to sym

ConditionTreeParser.from_plain_object(collection, filters)
# TODO: ConditionTreeValidator::validate($conditionTree, $collection);
end

def self.parse_caller(args)
unless args.dig(:headers, 'HTTP_AUTHORIZATION')
# TODO: replace by http exception
raise ForestException, 'You must be logged in to access at this resource.'
raise Http::Exceptions::HttpException.new(
401,
'You must be logged in to access at this resource.'
)
end

timezone = args[:params]['timezone']
Expand Down Expand Up @@ -125,6 +125,17 @@ def self.parse_sort(collection, args)

sort
end

def self.parse_segment(collection, args)
segment = args.dig(:params, :data, :attributes, :all_records_subset_query,
:segment) || args.dig(:params, :segment)

return unless segment

raise ForestException, "Invalid segment: #{segment}" unless collection.schema[:segments].include?(segment)

segment
end
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -29,19 +29,20 @@ def self.make_form_data_unsafe(raw_data)

def self.make_form_data_from_fields(datasource, fields)
data = {}
fields.each_value do |field|
next if Schema::GeneratorAction::DEFAULT_FIELDS.map { |f| f[:field] }.include?(field.field)

if field.reference && field.value
collection_name = field.reference.split('.').first
fields.each do |field|
next if Schema::GeneratorAction::DEFAULT_FIELDS.map { |f| f[:field] }.include?(field['field'])

if field['reference'] && field['value']
collection_name = field['reference'].split('.').first
collection = datasource.get_collection(collection_name)
data[field.field] = Utils::Id.unpack_id(collection, field.value)
elsif field.type == 'File'
data[field.field] = parse_data_uri(field.value)
elsif field.type.is_a?(Array) && field.type[0] == 'File'
data[field.field] = field.value.map { |v| parse_data_uri(v) }
data[field['field']] = Utils::Id.unpack_id(collection, field['value'])
elsif field['type'] == 'File'
data[field['field']] = parse_data_uri(field['value'])
elsif field['type'].is_a?(Array) && field['type'][0] == 'File'
data[field['field']] = field['value'].map { |v| parse_data_uri(v) }
else
data[field.field] = field.value
data[field['field']] = field['value']
end
end

Expand Down Expand Up @@ -83,7 +84,7 @@ def self.value_to_forest(field)

return field.value.select { |v| field.enum_values.include?(v) } if ActionFields.enum_list_field?(field)

return field.value.join('|') if ActionFields.collection_field?(field)
return field.value&.join('|') if ActionFields.collection_field?(field)

# return make_data_uri(field.value) if ActionFields.file_field?(field)
#
Expand Down
Loading
Loading